summaryrefslogtreecommitdiffstats
path: root/src/pybind/cephfs/cephfs.pyx
blob: 9a37448e1c25f0391e2dc212420600f36245ea8b (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
"""
This module is a thin wrapper around libcephfs.
"""

from cpython cimport PyObject, ref, exc
from libc.stdint cimport *
from libc.stdlib cimport malloc, realloc, free

from types cimport *
IF BUILD_DOC:
    include "mock_cephfs.pxi"
    cdef class Rados:
        cdef:
            rados_t cluster
ELSE:
    from c_cephfs cimport *
    from rados cimport Rados

from collections import namedtuple
from datetime import datetime
import os
import time

AT_SYMLINK_NOFOLLOW = 0x0100
AT_STATX_SYNC_TYPE  = 0x6000
AT_STATX_SYNC_AS_STAT = 0x0000
AT_STATX_FORCE_SYNC = 0x2000
AT_STATX_DONT_SYNC = 0x4000
cdef int AT_SYMLINK_NOFOLLOW_CDEF = AT_SYMLINK_NOFOLLOW
CEPH_STATX_BASIC_STATS = 0x7ff
cdef int CEPH_STATX_BASIC_STATS_CDEF = CEPH_STATX_BASIC_STATS
CEPH_STATX_MODE = 0x1
CEPH_STATX_NLINK = 0x2
CEPH_STATX_UID = 0x4
CEPH_STATX_GID = 0x8
CEPH_STATX_RDEV = 0x10
CEPH_STATX_ATIME = 0x20
CEPH_STATX_MTIME = 0x40
CEPH_STATX_CTIME = 0x80
CEPH_STATX_INO = 0x100
CEPH_STATX_SIZE = 0x200
CEPH_STATX_BLOCKS = 0x400
CEPH_STATX_BTIME = 0x800
CEPH_STATX_VERSION = 0x1000

FALLOC_FL_KEEP_SIZE = 0x01
FALLOC_FL_PUNCH_HOLE = 0x02
FALLOC_FL_NO_HIDE_STALE = 0x04

CEPH_SETATTR_MODE = 0x1
CEPH_SETATTR_UID = 0x2
CEPH_SETATTR_GID = 0x4
CEPH_SETATTR_MTIME = 0x8
CEPH_SETATTR_ATIME = 0x10
CEPH_SETATTR_SIZE  = 0x20
CEPH_SETATTR_CTIME = 0x40
CEPH_SETATTR_BTIME = 0x200

# errno definitions
cdef enum:
    CEPHFS_EBLOCKLISTED = 108
    CEPHFS_EPERM = 1
    CEPHFS_ESTALE = 116
    CEPHFS_ENOSPC = 28
    CEPHFS_ETIMEDOUT = 110
    CEPHFS_EIO = 5
    CEPHFS_ENOTCONN = 107
    CEPHFS_EEXIST = 17
    CEPHFS_EINTR = 4
    CEPHFS_EINVAL = 22
    CEPHFS_EBADF = 9
    CEPHFS_EROFS = 30
    CEPHFS_EAGAIN = 11
    CEPHFS_EACCES = 13
    CEPHFS_ELOOP = 40
    CEPHFS_EISDIR = 21
    CEPHFS_ENOENT = 2
    CEPHFS_ENOTDIR = 20
    CEPHFS_ENAMETOOLONG = 36
    CEPHFS_EBUSY = 16
    CEPHFS_EDQUOT = 122
    CEPHFS_EFBIG = 27
    CEPHFS_ERANGE = 34
    CEPHFS_ENXIO = 6
    CEPHFS_ECANCELED = 125
    CEPHFS_ENODATA = 61
    CEPHFS_EOPNOTSUPP = 95
    CEPHFS_EXDEV = 18
    CEPHFS_ENOMEM = 12
    CEPHFS_ENOTRECOVERABLE = 131
    CEPHFS_ENOSYS = 38
    CEPHFS_EWOULDBLOCK = CEPHFS_EAGAIN
    CEPHFS_ENOTEMPTY = 39
    CEPHFS_EDEADLK = 35
    CEPHFS_EDEADLOCK = CEPHFS_EDEADLK
    CEPHFS_EDOM = 33
    CEPHFS_EMLINK = 31
    CEPHFS_ETIME = 62
    CEPHFS_EOLDSNAPC = 85

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 Image.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()


class Error(Exception):
    def get_error_code(self):
        return 1


class LibCephFSStateError(Error):
    pass


class OSError(Error):
    def __init__(self, errno, strerror):
        super(OSError, self).__init__(errno, strerror)
        self.errno = errno
        self.strerror = "%s: %s" % (strerror, os.strerror(errno))

    def __str__(self):
        return '{} [Errno {}]'.format(self.strerror, self.errno)

    def get_error_code(self):
        return self.errno


class PermissionError(OSError):
    pass


class ObjectNotFound(OSError):
    pass


class NoData(OSError):
    pass


class ObjectExists(OSError):
    pass


class IOError(OSError):
    pass


class NoSpace(OSError):
    pass


class InvalidValue(OSError):
    pass


class OperationNotSupported(OSError):
    pass


class WouldBlock(OSError):
    pass


class OutOfRange(OSError):
    pass


class ObjectNotEmpty(OSError):
    pass

class NotDirectory(OSError):
    pass

class DiskQuotaExceeded(OSError):
    pass
class PermissionDenied(OSError):
    pass

cdef errno_to_exception =  {
    CEPHFS_EPERM      : PermissionError,
    CEPHFS_ENOENT     : ObjectNotFound,
    CEPHFS_EIO        : IOError,
    CEPHFS_ENOSPC     : NoSpace,
    CEPHFS_EEXIST     : ObjectExists,
    CEPHFS_ENODATA    : NoData,
    CEPHFS_EINVAL     : InvalidValue,
    CEPHFS_EOPNOTSUPP : OperationNotSupported,
    CEPHFS_ERANGE     : OutOfRange,
    CEPHFS_EWOULDBLOCK: WouldBlock,
    CEPHFS_ENOTEMPTY  : ObjectNotEmpty,
    CEPHFS_ENOTDIR    : NotDirectory,
    CEPHFS_EDQUOT     : DiskQuotaExceeded,
    CEPHFS_EACCES     : PermissionDenied,
}


cdef make_ex(ret, msg):
    """
    Translate a libcephfs 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](ret, msg)
    else:
        return OSError(ret, msg)


class DirEntry(namedtuple('DirEntry',
               ['d_ino', 'd_off', 'd_reclen', 'd_type', 'd_name'])):
    DT_DIR = 0x4
    DT_REG = 0x8
    DT_LNK = 0xA
    def is_dir(self):
        return self.d_type == self.DT_DIR

    def is_symbol_file(self):
        return self.d_type == self.DT_LNK

    def is_file(self):
        return self.d_type == self.DT_REG

StatResult = namedtuple('StatResult',
                        ["st_dev", "st_ino", "st_mode", "st_nlink", "st_uid",
                         "st_gid", "st_rdev", "st_size", "st_blksize",
                         "st_blocks", "st_atime", "st_mtime", "st_ctime"])

cdef class DirResult(object):
    cdef LibCephFS lib
    cdef ceph_dir_result* handle

# Bug in older Cython instances prevents this from being a static method.
#    @staticmethod
#    cdef create(LibCephFS lib, ceph_dir_result* handle):
#        d = DirResult()
#        d.lib = lib
#        d.handle = handle
#        return d

    def __dealloc__(self):
        self.close()

    def __enter__(self):
        if not self.handle:
            raise make_ex(CEPHFS_EBADF, "dir is not open")
        self.lib.require_state("mounted")
        with nogil:
            ceph_rewinddir(self.lib.cluster, self.handle)
        return self

    def __exit__(self, type_, value, traceback):
        self.close()
        return False

    def readdir(self):
        self.lib.require_state("mounted")

        with nogil:
            dirent = ceph_readdir(self.lib.cluster, self.handle)
        if not dirent:
            return None

        IF UNAME_SYSNAME == "FreeBSD" or UNAME_SYSNAME == "Darwin":
            return DirEntry(d_ino=dirent.d_ino,
                            d_off=0,
                            d_reclen=dirent.d_reclen,
                            d_type=dirent.d_type,
                            d_name=dirent.d_name)
        ELSE:
            return DirEntry(d_ino=dirent.d_ino,
                            d_off=dirent.d_off,
                            d_reclen=dirent.d_reclen,
                            d_type=dirent.d_type,
                            d_name=dirent.d_name)

    def close(self):
        if self.handle:
            self.lib.require_state("mounted")
            with nogil:
                ret = ceph_closedir(self.lib.cluster, self.handle)
            if ret < 0:
                raise make_ex(ret, "closedir failed")
            self.handle = NULL

    def rewinddir(self):
        if not self.handle:
            raise make_ex(CEPHFS_EBADF, "dir is not open")
        self.lib.require_state("mounted")
        with nogil:
            ceph_rewinddir(self.lib.cluster, self.handle)

    def telldir(self):
        if not self.handle:
            raise make_ex(CEPHFS_EBADF, "dir is not open")
        self.lib.require_state("mounted")
        with nogil:
            ret = ceph_telldir(self.lib.cluster, self.handle)
        if ret < 0:
            raise make_ex(ret, "telldir failed")
        return ret

    def seekdir(self, offset):
        if not self.handle:
            raise make_ex(CEPHFS_EBADF, "dir is not open")
        if not isinstance(offset, int):
            raise TypeError('offset must be an int')
        self.lib.require_state("mounted")
        cdef int64_t _offset = offset
        with nogil:
            ceph_seekdir(self.lib.cluster, self.handle, _offset)


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
    else:
        try:
            v = val.encode(encoding)
        except:
            raise TypeError('%s must be encodeable as a bytearray' % name)
        assert isinstance(v, bytes)
        return v

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: str or None
    """
    if val is None:
        return None

    return val.decode(encoding)

cdef timeval to_timeval(t):
    """
    return timeval equivalent from time
    """
    tt = int(t)
    cdef timeval buf = timeval(tt, (t - tt) * 1000000)
    return buf

cdef timespec to_timespec(t):
    """
    return timespec equivalent from time
    """
    tt = int(t)
    cdef timespec buf = timespec(tt, (t - tt) * 1000000000)
    return buf

cdef char* opt_str(s) except? NULL:
    if s is None:
        return NULL
    return s


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 range(len(list_bytes)):
        ret[i] = <char *>list_bytes[i]
    return ret


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 iovec * to_iovec(buffers) except NULL:
    cdef iovec *iov = <iovec *>malloc(len(buffers) * sizeof(iovec))
    cdef char *s = NULL
    if iov == NULL:
        raise MemoryError("malloc failed")
    for i in xrange(len(buffers)):
        s = <char*>buffers[i]
        iov[i] = [<void*>s, len(buffers[i])]
    return iov


cdef class LibCephFS(object):
    """libcephfs python wrapper"""

    cdef public object state
    cdef ceph_mount_info *cluster

    def require_state(self, *args):
        if self.state in args:
            return
        raise LibCephFSStateError("You cannot perform that operation on a "
                                  "CephFS object in state %s." % (self.state))

    def __cinit__(self, conf=None, conffile=None, auth_id=None, rados_inst=None):
        """Create a libcephfs wrapper

        :param conf dict opt: settings overriding the default ones and conffile
        :param conffile str opt: the path to ceph.conf to override the default settings
        :auth_id str opt: the id used to authenticate the client entity
        :rados_inst Rados opt: a rados.Rados instance
        """
        PyEval_InitThreads()
        self.state = "uninitialized"
        if rados_inst is not None:
            if auth_id is not None or conffile is not None or conf is not None:
                raise make_ex(CEPHFS_EINVAL,
                              "May not pass RADOS instance as well as other configuration")

            self.create_with_rados(rados_inst)
        else:
            self.create(conf, conffile, auth_id)

    def create_with_rados(self, Rados rados_inst):
        cdef int ret
        with nogil:
            ret = ceph_create_from_rados(&self.cluster, rados_inst.cluster)
        if ret != 0:
            raise Error("libcephfs_initialize failed with error code: %d" % ret)
        self.state = "configuring"

    NO_CONF_FILE = -1
    "special value that indicates no conffile should be read when creating a mount handle"
    DEFAULT_CONF_FILES = -2
    "special value that indicates the default conffiles should be read when creating a mount handle"

    def create(self, conf=None, conffile=NO_CONF_FILE, auth_id=None):
        """
        Create a mount handle for interacting with Ceph.  All libcephfs
        functions operate on a mount info handle.
        
        :param conf dict opt: settings overriding the default ones and conffile
        :param conffile Union[int,str], optional: the path to ceph.conf to override the default settings
        :auth_id str opt: the id used to authenticate the client entity
        """
        if conf is not None and not isinstance(conf, dict):
            raise TypeError("conf must be dict or None")
        cstr(conffile, 'configfile', opt=True)
        auth_id = cstr(auth_id, 'auth_id', opt=True)

        cdef:
            char* _auth_id = opt_str(auth_id)
            int ret

        with nogil:
            ret = ceph_create(&self.cluster, <const char*>_auth_id)
        if ret != 0:
            raise Error("libcephfs_initialize failed with error code: %d" % ret)

        self.state = "configuring"
        if conffile in (self.NO_CONF_FILE, None):
            pass
        elif conffile in (self.DEFAULT_CONF_FILES, ''):
            self.conf_read_file(None)
        else:
            self.conf_read_file(conffile)
        if conf is not None:
            for key, value in conf.items():
                self.conf_set(key, value)

    def get_fscid(self):
        """
        Return the file system id for this fs client.
        """
        self.require_state("mounted")
        with nogil:
            ret = ceph_get_fs_cid(self.cluster)
        if ret < 0:
            raise make_ex(ret, "error fetching fscid")
        return ret

    def get_addrs(self):
        """
        Get associated client addresses with this RADOS session.
        """
        self.require_state("mounted")

        cdef:
            char* addrs = NULL

        try:

            with nogil:
                ret = ceph_getaddrs(self.cluster, &addrs)
            if ret:
                raise make_ex(ret, "error calling getaddrs")

            return decode_cstr(addrs)
        finally:
            ceph_buffer_free(addrs)


    def conf_read_file(self, conffile=None):
        """
        Load the ceph configuration from the specified config file.
         
        :param conffile str opt: the path to ceph.conf to override the default settings
        """
        conffile = cstr(conffile, 'conffile', opt=True)
        cdef:
            char *_conffile = opt_str(conffile)
        with nogil:
            ret = ceph_conf_read_file(self.cluster, <const char*>_conffile)
        if ret != 0:
            raise make_ex(ret, "error calling conf_read_file")

    def conf_parse_argv(self, argv):
        """
        Parse the command line arguments and load the configuration parameters.
        
        :param argv: the argument list
        """
        self.require_state("configuring")
        cargv = cstr_list(argv, 'argv')
        cdef:
            int _argc = len(argv)
            char **_argv = to_bytes_array(cargv)

        try:
            with nogil:
                ret = ceph_conf_parse_argv(self.cluster, _argc,
                                           <const char **>_argv)
            if ret != 0:
                raise make_ex(ret, "error calling conf_parse_argv")
        finally:
            free(_argv)

    def shutdown(self):
        """
        Unmount and destroy the ceph mount handle.
        """
        if self.state in ["initialized", "mounted"]:
            with nogil:
                ceph_shutdown(self.cluster)
            self.state = "shutdown"

    def __enter__(self):
        self.mount()
        return self

    def __exit__(self, type_, value, traceback):
        self.shutdown()
        return False

    def __dealloc__(self):
        self.shutdown()

    def version(self):
        """
        Get the version number of the ``libcephfs`` C library.

        :returns: a tuple of ``(major, minor, extra)`` components of the
                  libcephfs version
        """
        cdef:
            int major = 0
            int minor = 0
            int extra = 0
        with nogil:
            ceph_version(&major, &minor, &extra)
        return (major, minor, extra)

    def conf_get(self, option):
        """
        Gets the configuration value as a string.
        
        :param option: the config option to get
        """
        self.require_state("configuring", "initialized", "mounted")

        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 = ceph_conf_get(self.cluster, _option, ret_buf, length)
                if ret == 0:
                    return decode_cstr(ret_buf)
                elif ret == -CEPHFS_ENAMETOOLONG:
                    length = length * 2
                elif ret == -CEPHFS_ENOENT:
                    return None
                else:
                    raise make_ex(ret, "error calling conf_get")
        finally:
            free(ret_buf)

    def conf_set(self, option, val):
        """
        Sets a configuration value from a string.
        
        :param option: the configuration option to set
        :param value: the value of the configuration option to set
        """
        self.require_state("configuring", "initialized", "mounted")

        option = cstr(option, 'option')
        val = cstr(val, 'val')
        cdef:
            char *_option = option
            char *_val = val

        with nogil:
            ret = ceph_conf_set(self.cluster, _option, _val)
        if ret != 0:
            raise make_ex(ret, "error calling conf_set")

    def set_mount_timeout(self, timeout):
        """
        Set mount timeout

        :param timeout: mount timeout
        """
        self.require_state("configuring", "initialized")
        if not isinstance(timeout, int):
            raise TypeError('timeout must be an integer')
        if timeout < 0:
            raise make_ex(CEPHFS_EINVAL, 'timeout must be greater than or equal to 0')
        cdef:
            uint32_t _timeout = timeout
        with nogil:
            ret = ceph_set_mount_timeout(self.cluster, _timeout)
        if ret != 0:
            raise make_ex(ret, "error setting mount timeout")

    def init(self):
        """
        Initialize the filesystem client (but do not mount the filesystem yet)
        """
        self.require_state("configuring")
        with nogil:
            ret = ceph_init(self.cluster)
        if ret != 0:
            raise make_ex(ret, "error calling ceph_init")
        self.state = "initialized"

    def mount(self, mount_root=None, filesystem_name=None):
        """
        Perform a mount using the path for the root of the mount.
        """
        if self.state == "configuring":
            self.init()
        self.require_state("initialized")

        # Configure which filesystem to mount if one was specified
        if filesystem_name is None:
            filesystem_name = b""
        else:
            filesystem_name = cstr(filesystem_name, 'filesystem_name')
        cdef:
            char *_filesystem_name = filesystem_name
        if filesystem_name:
            with nogil:
                ret = ceph_select_filesystem(self.cluster,
                        _filesystem_name)
            if ret != 0:
                raise make_ex(ret, "error calling ceph_select_filesystem")

        # Prepare mount_root argument, default to "/"
        root = b"/" if mount_root is None else mount_root
        cdef:
            char *_mount_root = root

        with nogil:
            ret = ceph_mount(self.cluster, _mount_root)
        if ret != 0:
            raise make_ex(ret, "error calling ceph_mount")
        self.state = "mounted"

    def unmount(self):
        """
        Unmount a mount handle.
        """
        self.require_state("mounted")
        with nogil:
            ret = ceph_unmount(self.cluster)
        if ret != 0:
            raise make_ex(ret, "error calling ceph_unmount")
        self.state = "initialized"

    def abort_conn(self):
        """
        Abort mds connections.
        """
        self.require_state("mounted")
        with nogil:
            ret = ceph_abort_conn(self.cluster)
        if ret != 0:
            raise make_ex(ret, "error calling ceph_abort_conn")
        self.state = "initialized"

    def get_instance_id(self):
        """
        Get a global id for current instance
        """
        self.require_state("initialized", "mounted")
        with nogil:
            ret = ceph_get_instance_id(self.cluster)
        return ret;

    def statfs(self, path):
        """
        Perform a statfs on the ceph file system.  This call fills in file system wide statistics
        into the passed in buffer.
        
        :param path: any path within the mounted filesystem
        """
        self.require_state("mounted")
        path = cstr(path, 'path')
        cdef:
            char* _path = path
            statvfs statbuf

        with nogil:
            ret = ceph_statfs(self.cluster, _path, &statbuf)
        if ret < 0:
            raise make_ex(ret, "statfs failed: %s" % path)
        return {'f_bsize': statbuf.f_bsize,
                'f_frsize': statbuf.f_frsize,
                'f_blocks': statbuf.f_blocks,
                'f_bfree': statbuf.f_bfree,
                'f_bavail': statbuf.f_bavail,
                'f_files': statbuf.f_files,
                'f_ffree': statbuf.f_ffree,
                'f_favail': statbuf.f_favail,
                'f_fsid': statbuf.f_fsid,
                'f_flag': statbuf.f_flag,
                'f_namemax': statbuf.f_namemax}

    def sync_fs(self):
        """
        Synchronize all filesystem data to persistent media
        """
        self.require_state("mounted")
        with nogil:
            ret = ceph_sync_fs(self.cluster)
        if ret < 0:
            raise make_ex(ret, "sync_fs failed")

    def fsync(self, int fd, int syncdataonly):
        """
        Synchronize an open file to persistent media.
        
        :param fd: the file descriptor of the file to sync.
        :param syncdataonly: a boolean whether to synchronize metadata and data (0)
                             or just data (1).
        """
        self.require_state("mounted")
        with nogil:
            ret = ceph_fsync(self.cluster, fd, syncdataonly)
        if ret < 0:
            raise make_ex(ret, "fsync failed")

    def lazyio(self, fd, enable):
        """
        Enable/disable lazyio for the file.

        :param fd: the file descriptor of the file for which to enable lazio.
        :param enable: a boolean to enable lazyio or disable lazyio.
        """

        self.require_state("mounted")
        if not isinstance(fd, int):
            raise TypeError('fd must be an int')
        if not isinstance(enable, int):
            raise TypeError('enable must be an int')

        cdef:
            int _fd = fd
            int _enable = enable

        with nogil:
            ret = ceph_lazyio(self.cluster, _fd, _enable)
        if ret < 0:
            raise make_ex(ret, "lazyio failed")

    def lazyio_propagate(self, fd, offset, count):
        """
        Flushes the write buffer for the file thereby propogating the buffered write to the file.

        :param fd: the file descriptor of the file to sync.
        :param offset: the byte range starting.
        :param count: the number of bytes starting from offset.
        """

        self.require_state("mounted")
        if not isinstance(fd, int):
            raise TypeError('fd must be an int')
        if not isinstance(offset, int):
            raise TypeError('offset must be an int')
        if not isinstance(count, int):
            raise TypeError('count must be an int')

        cdef:
            int _fd = fd
            int64_t _offset = offset
            size_t _count = count

        with nogil:
            ret = ceph_lazyio_propagate(self.cluster, _fd, _offset, _count)
        if ret < 0:
            raise make_ex(ret, "lazyio_propagate failed")

    def lazyio_synchronize(self, fd, offset, count):
        """
        Flushes the write buffer for the file and invalidate the read cache. This allows a
        subsequent read operation to read and cache data directly from the file and hence
        everyone's propagated writes would be visible.

        :param fd: the file descriptor of the file to sync.
        :param offset: the byte range starting.
        :param count: the number of bytes starting from offset.
        """

        self.require_state("mounted")
        if not isinstance(fd, int):
            raise TypeError('fd must be an int')
        if not isinstance(offset, int):
            raise TypeError('offset must be an int')
        if not isinstance(count, int):
            raise TypeError('count must be an int')

        cdef:
            int _fd = fd
            int64_t _offset = offset
            size_t _count = count

        with nogil:
            ret = ceph_lazyio_synchronize(self.cluster, _fd, _offset, _count)
        if ret < 0:
            raise make_ex(ret, "lazyio_synchronize failed")

    def fallocate(self, fd, offset, length, mode=0):
        """
        Preallocate or release disk space for the file for the byte range.

        :param fd: the file descriptor of the file to fallocate.
        :param mode: the flags determines the operation to be performed on the given
                     range. default operation (0) allocate and initialize to zero
                     the file in the byte range, and the file size will be changed
                     if offset + length is greater than the file size. if the
                     FALLOC_FL_KEEP_SIZE flag is specified in the mode, the file size
                     will not be changed. if the FALLOC_FL_PUNCH_HOLE flag is specified
                     in the mode, the operation is deallocate space and zero the byte range.
        :param offset: the byte range starting.
        :param length: the length of the range.
        """

        self.require_state("mounted")
        if not isinstance(fd, int):
            raise TypeError('fd must be an int')
        if not isinstance(mode, int):
            raise TypeError('mode must be an int')
        if not isinstance(offset, int):
            raise TypeError('offset must be an int')
        if not isinstance(length, int):
            raise TypeError('length must be an int')

        cdef:
            int _fd = fd
            int _mode = mode
            int64_t _offset = offset
            int64_t _length = length

        with nogil:
            ret = ceph_fallocate(self.cluster, _fd, _mode, _offset, _length)
        if ret < 0:
            raise make_ex(ret, "fallocate failed")

    def getcwd(self):
        """
        Get the current working directory.
        
        :rtype the path to the current working directory
        """
        self.require_state("mounted")
        with nogil:
            ret = ceph_getcwd(self.cluster)
        return ret

    def chdir(self, path):
        """
        Change the current working directory.
        
        :param path the path to the working directory to change into.
        """
        self.require_state("mounted")

        path = cstr(path, 'path')
        cdef char* _path = path
        with nogil:
            ret = ceph_chdir(self.cluster, _path)
        if ret < 0:
            raise make_ex(ret, "chdir failed")

    def opendir(self, path):
        """
        Open the given directory.
        
        :param path: the path name of the directory to open.  Must be either an absolute path
                     or a path relative to the current working directory.
        :rtype handle: the open directory stream handle
        """
        self.require_state("mounted")

        path = cstr(path, 'path')
        cdef:
            char* _path = path
            ceph_dir_result* handle
        with nogil:
            ret = ceph_opendir(self.cluster, _path, &handle);
        if ret < 0:
            raise make_ex(ret, "opendir failed at {}".format(path.decode('utf-8')))
        d = DirResult()
        d.lib = self
        d.handle = handle
        return d

    def readdir(self, DirResult handle):
        """
        Get the next entry in an open directory.
        
        :param handle: the open directory stream handle
        :rtype dentry: the next directory entry or None if at the end of the
                       directory (or the directory is empty.  This pointer
                       should not be freed by the caller, and is only safe to
                       access between return and the next call to readdir or
                       closedir.
        """
        self.require_state("mounted")

        return handle.readdir()

    def closedir(self, DirResult handle):
        """
        Close the open directory.
        
        :param handle: the open directory stream handle
        """
        self.require_state("mounted")

        return handle.close()

    def rewinddir(self, DirResult handle):
        """
        Rewind the directory stream to the beginning of the directory.

        :param handle: the open directory stream handle
        """
        return handle.rewinddir()

    def telldir(self, DirResult handle):
        """
        Get the current position of a directory stream.

        :param handle: the open directory stream handle
        :return value: The position of the directory stream. Note that the offsets
                       returned by ceph_telldir do not have a particular order (cannot
                       be compared with inequality).
        """
        return handle.telldir()

    def seekdir(self, DirResult handle, offset):
        """
        Move the directory stream to a position specified by the given offset.

        :param handle: the open directory stream handle
        :param offset: the position to move the directory stream to. This offset should be
                       a value returned by telldir. Note that this value does not refer to
                       the nth entry in a directory, and can not be manipulated with plus
                       or minus.
        """
        return handle.seekdir(offset)

    def mkdir(self, path, mode):
        """
        Create a directory.
 
        :param path: the path of the directory to create.  This must be either an
                     absolute path or a relative path off of the current working directory.
        :param mode: the permissions the directory should have once created.
        """

        self.require_state("mounted")
        path = cstr(path, 'path')
        if not isinstance(mode, int):
            raise TypeError('mode must be an int')
        cdef:
            char* _path = path
            int _mode = mode
        with nogil:
            ret = ceph_mkdir(self.cluster, _path, _mode)
        if ret < 0:
            raise make_ex(ret, "error in mkdir {}".format(path.decode('utf-8')))

    def mksnap(self, path, name, mode, metadata={}):
        """
        Create a snapshot.

        :param path: path of the directory to snapshot.
        :param name: snapshot name
        :param mode: permission of the snapshot
        :param metadata: metadata key/value to store with the snapshot

        :raises: :class: `TypeError`
        :raises: :class: `Error`
        :returns: int: 0 on success
        """

        self.require_state("mounted")
        path = cstr(path, 'path')
        name = cstr(name, 'name')
        if not isinstance(mode, int):
            raise TypeError('mode must be an int')
        if not isinstance(metadata, dict):
            raise TypeError('metadata must be an dictionary')
        md = {}
        for key, value in metadata.items():
            if not isinstance(key, str) or not isinstance(value, str):
                raise TypeError('metadata key and values should be strings')
            md[key.encode('utf-8')] = value.encode('utf-8')
        cdef:
            char* _path = path
            char* _name = name
            int _mode = mode
            size_t nr = len(md)
            snap_metadata *_snap_meta = <snap_metadata *>malloc(nr * sizeof(snap_metadata))
        if nr and _snap_meta == NULL:
            raise MemoryError("malloc failed")
        i = 0
        for key, value in md.items():
            _snap_meta[i] = snap_metadata(<char*>key, <char*>value)
            i += 1
        with nogil:
            ret = ceph_mksnap(self.cluster, _path, _name, _mode, _snap_meta, nr)
        free(_snap_meta)
        if ret < 0:
            raise make_ex(ret, "mksnap error")
        return 0

    def rmsnap(self, path, name):
        """
        Remove a snapshot.

        :param path: path of the directory for removing snapshot
        :param name: snapshot name

        :raises: :class: `Error`
        :returns: int: 0 on success
        """
        self.require_state("mounted")
        path = cstr(path, 'path')
        name = cstr(name, 'name')
        cdef:
            char* _path = path
            char* _name = name
        ret = ceph_rmsnap(self.cluster, _path, _name)
        if ret < 0:
            raise make_ex(ret, "rmsnap error")
        return 0

    def snap_info(self, path):
        """
        Fetch sapshot info

        :param path: snapshot path

        :raises: :class: `Error`
        :returns: dict: snapshot metadata
        """
        self.require_state("mounted")
        path = cstr(path, 'path')
        cdef:
            char* _path = path
            snap_info info
        ret = ceph_get_snap_info(self.cluster, _path, &info)
        if ret < 0:
            raise make_ex(ret, "snap_info error")
        md = {}
        if info.nr_snap_metadata:
            md = {snap_meta.key.decode('utf-8'): snap_meta.value.decode('utf-8') for snap_meta in
                  info.snap_metadata[:info.nr_snap_metadata]}
            ceph_free_snap_info_buffer(&info)
        return {'id': info.id, 'metadata': md}

    def chmod(self, path, mode) :
        """
        Change directory mode.

        :param path: the path of the directory to create.  This must be either an
                     absolute path or a relative path off of the current working directory.
        :param mode: the permissions the directory should have once created.
        """
        self.require_state("mounted")
        path = cstr(path, 'path')
        if not isinstance(mode, int):
            raise TypeError('mode must be an int')
        cdef:
            char* _path = path
            int _mode = mode
        with nogil:
            ret = ceph_chmod(self.cluster, _path, _mode)
        if ret < 0:
            raise make_ex(ret, "error in chmod {}".format(path.decode('utf-8')))

    def lchmod(self, path, mode) -> None:
        """
        Change file mode. If the path is a symbolic link, it won't be dereferenced.

        :param path: the path of the file. This must be either an absolute path or
                     a relative path off of the current working directory.
        :param mode: the permissions to be set .
        """
        self.require_state("mounted")
        path = cstr(path, 'path')
        if not isinstance(mode, int):
            raise TypeError('mode must be an int')
        cdef:
            char* _path = path
            int _mode = mode
        with nogil:
            ret = ceph_lchmod(self.cluster, _path, _mode)
        if ret < 0:
            raise make_ex(ret, "error in chmod {}".format(path.decode('utf-8')))

    def fchmod(self, fd, mode) :
        """
        Change file mode based on fd.
        :param fd: the file descriptor of the file to change file mode
        :param mode: the permissions to be set.
        """
        self.require_state("mounted")
        if not isinstance(fd, int):
            raise TypeError('fd must be an int')
        if not isinstance(mode, int):
            raise TypeError('mode must be an int')
        cdef:
            int _fd = fd
            int _mode = mode
        with nogil:
            ret = ceph_fchmod(self.cluster, _fd, _mode)
        if ret < 0:
            raise make_ex(ret, "error in fchmod")

    def chown(self, path, uid, gid, follow_symlink=True):
        """
        Change directory ownership

        :param path: the path of the directory to change.
        :param uid: the uid to set
        :param gid: the gid to set
        :param follow_symlink: perform the operation on the target file if @path
                               is a symbolic link (default)
        """
        self.require_state("mounted")
        path = cstr(path, 'path')
        if not isinstance(uid, int):
            raise TypeError('uid must be an int')
        elif not isinstance(gid, int):
            raise TypeError('gid must be an int')

        cdef:
            char* _path = path
            int _uid = uid
            int _gid = gid
        if follow_symlink:
            with nogil:
                ret = ceph_chown(self.cluster, _path, _uid, _gid)
        else:
            with nogil:
                ret = ceph_lchown(self.cluster, _path, _uid, _gid)
        if ret < 0:
            raise make_ex(ret, "error in chown {}".format(path.decode('utf-8')))

    def lchown(self, path, uid, gid):
        """
        Change ownership of a symbolic link
        :param path: the path of the symbolic link to change.
        :param uid: the uid to set
        :param gid: the gid to set
        """
        self.chown(path, uid, gid, follow_symlink=False)

    def fchown(self, fd, uid, gid):
        """
        Change file ownership
        :param fd: the file descriptor of the file to change ownership
        :param uid: the uid to set
        :param gid: the gid to set
        """
        self.require_state("mounted")
        if not isinstance(fd, int):
            raise TypeError('fd must be an int')
        if not isinstance(uid, int):
            raise TypeError('uid must be an int')
        elif not isinstance(gid, int):
            raise TypeError('gid must be an int')

        cdef:
            int _fd = fd
            int _uid = uid
            int _gid = gid
        with nogil:
            ret = ceph_fchown(self.cluster, _fd, _uid, _gid)
        if ret < 0:
            raise make_ex(ret, "error in fchown")

    def mkdirs(self, path, mode):
        """
        Create multiple directories at once.

        :param path: the full path of directories and sub-directories that should
                     be created.
        :param mode: the permissions the directory should have once created
        """
        self.require_state("mounted")
        path = cstr(path, 'path')
        if not isinstance(mode, int):
            raise TypeError('mode must be an int')
        cdef:
            char* _path = path
            int _mode = mode

        with nogil:
            ret = ceph_mkdirs(self.cluster, _path, _mode)
        if ret < 0:
            raise make_ex(ret, "error in mkdirs {}".format(path.decode('utf-8')))

    def rmdir(self, path):
        """
        Remove a directory.
         
        :param path: the path of the directory to remove.
        """
        self.require_state("mounted")
        path = cstr(path, 'path')
        cdef char* _path = path
        ret = ceph_rmdir(self.cluster, _path)
        if ret < 0:
            raise make_ex(ret, "error in rmdir {}".format(path.decode('utf-8')))

    def open(self, path, flags, mode=0):
        """
        Create and/or open a file.
         
        :param path: the path of the file to open.  If the flags parameter includes O_CREAT,
                     the file will first be created before opening.
        :param flags: set of option masks that control how the file is created/opened.
        :param mode: the permissions to place on the file if the file does not exist and O_CREAT
                     is specified in the flags.
        """
        self.require_state("mounted")
        path = cstr(path, 'path')

        if not isinstance(mode, int):
            raise TypeError('mode must be an int')
        if isinstance(flags, str):
            cephfs_flags = 0
            if flags == '':
                cephfs_flags = os.O_RDONLY
            else:
                access_flags = 0;
                for c in flags:
                    if c == 'r':
                        access_flags = 1;
                    elif c == 'w':
                        access_flags = 2;
                        cephfs_flags |= os.O_TRUNC | os.O_CREAT
                    elif access_flags > 0 and c == '+':
                        access_flags = 3;
                    else:
                        raise make_ex(CEPHFS_EOPNOTSUPP,
                                      "open flags doesn't support %s" % c)

                if access_flags == 1:
                    cephfs_flags |= os.O_RDONLY;
                elif access_flags == 2:
                    cephfs_flags |= os.O_WRONLY;
                else:
                    cephfs_flags |= os.O_RDWR;

        elif isinstance(flags, int):
            cephfs_flags = flags
        else:
            raise TypeError("flags must be a string or an integer")

        cdef:
            char* _path = path
            int _flags = cephfs_flags
            int _mode = mode

        with nogil:
            ret = ceph_open(self.cluster, _path, _flags, _mode)
        if ret < 0:
            raise make_ex(ret, "error in open {}".format(path.decode('utf-8')))
        return ret

    def close(self, fd):
        """
        Close the open file.
        
        :param fd: the file descriptor referring to the open file.
        """

        self.require_state("mounted")
        if not isinstance(fd, int):
            raise TypeError('fd must be an int')
        cdef int _fd = fd
        with nogil:
            ret = ceph_close(self.cluster, _fd)
        if ret < 0:
            raise make_ex(ret, "error in close")

    def read(self, fd, offset, l):
        """
        Read data from the file.
 
        :param fd: the file descriptor of the open file to read from.
        :param offset: the offset in the file to read from.  If this value is negative, the
                       function reads from the current offset of the file descriptor.
        :param l: the flag to indicate what type of seeking to perform
        """     
        self.require_state("mounted")
        if not isinstance(offset, int):
            raise TypeError('offset must be an int')
        if not isinstance(l, int):
            raise TypeError('l must be an int')
        if not isinstance(fd, int):
            raise TypeError('fd must be an int')
        cdef:
            int _fd = fd
            int64_t _offset = offset
            int64_t _length = l

            char *ret_buf
            PyObject* ret_s = NULL

        ret_s = PyBytes_FromStringAndSize(NULL, _length)
        try:
            ret_buf = PyBytes_AsString(ret_s)
            with nogil:
                ret = ceph_read(self.cluster, _fd, ret_buf, _length, _offset)
            if ret < 0:
                raise make_ex(ret, "error in read")

            if ret != _length:
                _PyBytes_Resize(&ret_s, ret)

            return <object>ret_s
        finally:
            # We DECREF unconditionally: the cast to object above will have
            # INCREFed if necessary. This also takes care of exceptions,
            # including if _PyString_Resize fails (that will free the string
            # itself and set ret_s to NULL, hence XDECREF).
            ref.Py_XDECREF(ret_s)

    def preadv(self, fd, buffers, offset):
        """
        Write data to a file.

        :param fd: the file descriptor of the open file to read from
        :param buffers: the list of byte object to read from the file
        :param offset: the offset of the file read from.  If this value is negative, the
                       function reads from the current offset of the file descriptor.
        """
        self.require_state("mounted")
        if not isinstance(fd, int):
            raise TypeError('fd must be an int')
        if not isinstance(buffers, list):
            raise TypeError('buffers must be a list')
        for buf in buffers:
            if not isinstance(buf, bytearray):
                raise TypeError('buffers must be a list of bytes')
        if not isinstance(offset, int):
            raise TypeError('offset must be an int')

        cdef:
            int _fd = fd
            int _iovcnt = len(buffers)
            int64_t _offset = offset
            iovec *_iov = to_iovec(buffers)
        try:
            with nogil:
                ret = ceph_preadv(self.cluster, _fd, _iov, _iovcnt, _offset)
            if ret < 0:
                raise make_ex(ret, "error in preadv")
            return ret
        finally:
            free(_iov)

    def write(self, fd, buf, offset):
        """
        Write data to a file.
       
        :param fd: the file descriptor of the open file to write to
        :param buf: the bytes to write to the file
        :param offset: the offset of the file write into.  If this value is negative, the
                       function writes to the current offset of the file descriptor.
        """
        self.require_state("mounted")
        if not isinstance(fd, int):
            raise TypeError('fd must be an int')
        if not isinstance(buf, bytes):
            raise TypeError('buf must be a bytes')
        if not isinstance(offset, int):
            raise TypeError('offset must be an int')

        cdef:
            int _fd = fd
            char *_data = buf
            int64_t _offset = offset

            size_t length = len(buf)

        with nogil:
            ret = ceph_write(self.cluster, _fd, _data, length, _offset)
        if ret < 0:
            raise make_ex(ret, "error in write")
        return ret

    def pwritev(self, fd, buffers, offset):
        """
        Write data to a file.

        :param fd: the file descriptor of the open file to write to
        :param buffers: the list of byte object to write to the file
        :param offset: the offset of the file write into.  If this value is negative, the
                       function writes to the current offset of the file descriptor.
        """
        self.require_state("mounted")
        if not isinstance(fd, int):
            raise TypeError('fd must be an int')
        if not isinstance(buffers, list):
            raise TypeError('buffers must be a list')
        for buf in buffers:
            if not isinstance(buf, bytes):
                raise TypeError('buffers must be a list of bytes')
        if not isinstance(offset, int):
            raise TypeError('offset must be an int')

        cdef:
            int _fd = fd
            int _iovcnt = len(buffers)
            int64_t _offset = offset
            iovec *_iov = to_iovec(buffers)
        try:
            with nogil:
                ret = ceph_pwritev(self.cluster, _fd, _iov, _iovcnt, _offset)
            if ret < 0:
                raise make_ex(ret, "error in pwritev")
            return ret
        finally:
            free(_iov)

    def flock(self, fd, operation, owner):
        """
        Apply or remove an advisory lock.
        
        :param fd: the open file descriptor to change advisory lock.
        :param operation: the advisory lock operation to be performed on the file
        :param owner: the user-supplied owner identifier (an arbitrary integer)
        """
        self.require_state("mounted")
        if not isinstance(fd, int):
            raise TypeError('fd must be an int')
        if not isinstance(operation, int):
            raise TypeError('operation must be an int')

        cdef:
            int _fd = fd
            int _op = operation
            uint64_t _owner = owner

        with nogil:
            ret = ceph_flock(self.cluster, _fd, _op, _owner)
        if ret < 0:
            raise make_ex(ret, "error in write")
        return ret

    def truncate(self, path, size):
        """
        Truncate the file to the given size.  If this operation causes the
        file to expand, the empty bytes will be filled in with zeros.

        :param path: the path to the file to truncate.
        :param size: the new size of the file.
        """

        if not isinstance(size, int):
            raise TypeError('size must be a int')

        statx_dict = dict()
        statx_dict["size"] = size
        self.setattrx(path, statx_dict, CEPH_SETATTR_SIZE, AT_SYMLINK_NOFOLLOW)

    def ftruncate(self, fd, size):
        """
        Truncate the file to the given size.  If this operation causes the
        file to expand, the empty bytes will be filled in with zeros.

        :param path: the path to the file to truncate.
        :param size: the new size of the file.
        """

        if not isinstance(size, int):
            raise TypeError('size must be a int')

        statx_dict = dict()
        statx_dict["size"] = size
        self.fsetattrx(fd, statx_dict, CEPH_SETATTR_SIZE)

    def mknod(self, path, mode, rdev=0):
        """
        Make a block or character special file.

        :param path: the path to the special file.
        :param mode: the permissions to use and the type of special file. The type can be
                     one of stat.S_IFREG, stat.S_IFCHR, stat.S_IFBLK, stat.S_IFIFO. Both
                     should be combined using bitwise OR.
        :param rdev: If the file type is stat.S_IFCHR or stat.S_IFBLK then this parameter
                     specifies the major and minor numbers of the newly created device
                     special file. Otherwise, it is ignored.
        """
        self.require_state("mounted")
        path = cstr(path, 'path')

        if not isinstance(mode, int):
            raise TypeError('mode must be an int')
        if not isinstance(rdev, int):
            raise TypeError('rdev must be an int')

        cdef:
            char* _path = path
            mode_t _mode = mode
            dev_t _rdev = rdev

        with nogil:
            ret = ceph_mknod(self.cluster, _path, _mode, _rdev)
        if ret < 0:
            raise make_ex(ret, "error in mknod {}".format(path.decode('utf-8')))

    def getxattr(self, path, name, size=255, follow_symlink=True):
        """
         Get an extended attribute.
         
         :param path: the path to the file
         :param name: the name of the extended attribute to get
         :param size: the size of the pre-allocated buffer
        """ 
        self.require_state("mounted")

        path = cstr(path, 'path')
        name = cstr(name, 'name')

        cdef:
            char* _path = path
            char* _name = name

            size_t ret_length = size
            char *ret_buf = NULL

        try:
            ret_buf = <char *>realloc_chk(ret_buf, ret_length)
            if follow_symlink:
                with nogil:
                    ret = ceph_getxattr(self.cluster, _path, _name, ret_buf,
                                        ret_length)
            else:
                with nogil:
                    ret = ceph_lgetxattr(self.cluster, _path, _name, ret_buf,
                                         ret_length)

            if ret < 0:
                raise make_ex(ret, "error in getxattr")

            return ret_buf[:ret]
        finally:
            free(ret_buf)

    def fgetxattr(self, fd, name, size=255):
        """
         Get an extended attribute given the fd of a file.

         :param fd: the open file descriptor referring to the file
         :param name: the name of the extended attribute to get
         :param size: the size of the pre-allocated buffer
        """
        self.require_state("mounted")

        if not isinstance(fd, int):
            raise TypeError('fd must be an int')
        name = cstr(name, 'name')

        cdef:
            int _fd = fd
            char* _name = name

            size_t ret_length = size
            char *ret_buf = NULL

        try:
            ret_buf = <char *>realloc_chk(ret_buf, ret_length)
            with nogil:
                ret = ceph_fgetxattr(self.cluster, _fd, _name, ret_buf,
                                    ret_length)

            if ret < 0:
                raise make_ex(ret, "error in fgetxattr")

            return ret_buf[:ret]
        finally:
            free(ret_buf)

    def lgetxattr(self, path, name, size=255):
        """
         Get an extended attribute without following symbolic links. This
         function is identical to ceph_getxattr, but if the path refers to
         a symbolic link, we get the extended attributes of the symlink
         rather than the attributes of the file it points to.

         :param path: the path to the file
         :param name: the name of the extended attribute to get
         :param size: the size of the pre-allocated buffer
        """

        return self.getxattr(path, name, size=size, follow_symlink=False)

    def setxattr(self, path, name, value, flags, follow_symlink=True):
        """
        Set an extended attribute on a file.

       :param path: the path to the file.
       :param name: the name of the extended attribute to set.
       :param value: the bytes of the extended attribute value
       """
        self.require_state("mounted")

        name = cstr(name, 'name')
        path = cstr(path, 'path')
        if not isinstance(flags, int):
            raise TypeError('flags must be a int')
        if not isinstance(value, bytes):
            raise TypeError('value must be a bytes')

        cdef:
            char *_path = path
            char *_name = name
            char *_value = value
            size_t _value_len = len(value)
            int _flags = flags

        if follow_symlink:
            with nogil:
                ret = ceph_setxattr(self.cluster, _path, _name,
                                    _value, _value_len, _flags)
        else:
            with nogil:
                ret = ceph_lsetxattr(self.cluster, _path, _name,
                                    _value, _value_len, _flags)

        if ret < 0:
            raise make_ex(ret, "error in setxattr")

    def fsetxattr(self, fd, name, value, flags):
        """
        Set an extended attribute on a file.

        :param fd: the open file descriptor referring to the file.
        :param name: the name of the extended attribute to set.
        :param value: the bytes of the extended attribute value
        """
        self.require_state("mounted")

        name = cstr(name, 'name')
        if not isinstance(fd, int):
            raise TypeError('fd must be an int')
        if not isinstance(flags, int):
            raise TypeError('flags must be a int')
        if not isinstance(value, bytes):
            raise TypeError('value must be a bytes')

        cdef:
            int _fd = fd
            char *_name = name
            char *_value = value
            size_t _value_len = len(value)
            int _flags = flags

        with nogil:
            ret = ceph_fsetxattr(self.cluster, _fd, _name,
                                 _value, _value_len, _flags)
        if ret < 0:
            raise make_ex(ret, "error in fsetxattr")

    def lsetxattr(self, path, name, value, flags):
        """
        Set an extended attribute on a file but do not follow symbolic link.

        :param path: the path to the file.
        :param name: the name of the extended attribute to set.
        :param value: the bytes of the extended attribute value
        """

        self.setxattr(path, name, value, flags, follow_symlink=False)

    def removexattr(self, path, name, follow_symlink=True):
        """
        Remove an extended attribute of a file.

        :param path: path of the file.
        :param name: name of the extended attribute to remove.
        """
        self.require_state("mounted")

        name = cstr(name, 'name')
        path = cstr(path, 'path')

        cdef:
            char *_path = path
            char *_name = name

        if follow_symlink:
            with nogil:
                ret = ceph_removexattr(self.cluster, _path, _name)
        else:
            with nogil:
                ret = ceph_lremovexattr(self.cluster, _path, _name)

        if ret < 0:
            raise make_ex(ret, "error in removexattr")

    def fremovexattr(self, fd, name):
        """
        Remove an extended attribute of a file.

        :param fd: the open file descriptor referring to the file.
        :param name: name of the extended attribute to remove.
        """
        self.require_state("mounted")

        if not isinstance(fd, int):
            raise TypeError('fd must be an int')
        name = cstr(name, 'name')

        cdef:
            int _fd = fd
            char *_name = name

        with nogil:
            ret = ceph_fremovexattr(self.cluster, _fd, _name)
        if ret < 0:
            raise make_ex(ret, "error in fremovexattr")

    def lremovexattr(self, path, name):
        """
        Remove an extended attribute of a file but do not follow symbolic link.

        :param path: path of the file.
        :param name: name of the extended attribute to remove.
        """
        self.removexattr(path, name, follow_symlink=False)

    def listxattr(self, path, size=65536, follow_symlink=True):
        """
        List the extended attribute keys set on a file.

        :param path: path of the file.
        :param size: the size of list buffer to be filled with extended attribute keys.
        """
        self.require_state("mounted")

        path = cstr(path, 'path')

        cdef:
            char *_path = path
            char *ret_buf = NULL
            size_t ret_length = size

        try:
            ret_buf = <char *>realloc_chk(ret_buf, ret_length)
            if follow_symlink:
                with nogil:
                    ret = ceph_listxattr(self.cluster, _path, ret_buf, ret_length)
            else:
                with nogil:
                    ret = ceph_llistxattr(self.cluster, _path, ret_buf, ret_length)

            if ret < 0:
                raise make_ex(ret, "error in listxattr")

            return ret, ret_buf[:ret]
        finally:
            free(ret_buf)

    def flistxattr(self, fd, size=65536):
        """
        List the extended attribute keys set on a file.

        :param fd: the open file descriptor referring to the file.
        :param size: the size of list buffer to be filled with extended attribute keys.
        """
        self.require_state("mounted")

        if not isinstance(fd, int):
            raise TypeError('fd must be an int')

        cdef:
            int _fd = fd
            char *ret_buf = NULL
            size_t ret_length = size

        try:
            ret_buf = <char *>realloc_chk(ret_buf, ret_length)
            with nogil:
                ret = ceph_flistxattr(self.cluster, _fd, ret_buf, ret_length)

            if ret < 0:
                raise make_ex(ret, "error in flistxattr")

            return ret, ret_buf[:ret]
        finally:
            free(ret_buf)

    def llistxattr(self, path, size=65536):
        """
        List the extended attribute keys set on a file but do not follow symbolic link.

        :param path: path of the file.
        :param size: the size of list buffer to be filled with extended attribute keys.
        """

        return self.listxattr(path, size=size, follow_symlink=False)

    def stat(self, path, follow_symlink=True):
        """
        Get a file's extended statistics and attributes.
        
        :param path: the file or directory to get the statistics of.
        """
        self.require_state("mounted")
        path = cstr(path, 'path')

        cdef:
            char* _path = path
            statx stx

        if follow_symlink:
            with nogil:
                ret = ceph_statx(self.cluster, _path, &stx,
                                 CEPH_STATX_BASIC_STATS_CDEF, 0)
        else:
            with nogil:
                ret = ceph_statx(self.cluster, _path, &stx,
                                 CEPH_STATX_BASIC_STATS_CDEF, AT_SYMLINK_NOFOLLOW_CDEF)

        if ret < 0:
            raise make_ex(ret, "error in stat: {}".format(path.decode('utf-8')))
        return StatResult(st_dev=stx.stx_dev, st_ino=stx.stx_ino,
                          st_mode=stx.stx_mode, st_nlink=stx.stx_nlink,
                          st_uid=stx.stx_uid, st_gid=stx.stx_gid,
                          st_rdev=stx.stx_rdev, st_size=stx.stx_size,
                          st_blksize=stx.stx_blksize,
                          st_blocks=stx.stx_blocks,
                          st_atime=datetime.fromtimestamp(stx.stx_atime.tv_sec),
                          st_mtime=datetime.fromtimestamp(stx.stx_mtime.tv_sec),
                          st_ctime=datetime.fromtimestamp(stx.stx_ctime.tv_sec))

    def lstat(self, path):
        """
        Get a file's extended statistics and attributes. If the file is a
        symbolic link, return the information of the link itself rather than
        the information of the file it points to.

        :param path: the file or directory to get the statistics of.
        """
        return self.stat(path, follow_symlink=False)

    def fstat(self, fd):
        """
        Get an open file's extended statistics and attributes.

        :param fd: the file descriptor of the file to get statistics of.
         """
        self.require_state("mounted")
        if not isinstance(fd, int):
            raise TypeError('fd must be an int')

        cdef:
            int _fd = fd
            statx stx

        with nogil:
            ret = ceph_fstatx(self.cluster, _fd, &stx,
                              CEPH_STATX_BASIC_STATS_CDEF, 0)
        if ret < 0:
            raise make_ex(ret, "error in fsat")
        return StatResult(st_dev=stx.stx_dev, st_ino=stx.stx_ino,
                          st_mode=stx.stx_mode, st_nlink=stx.stx_nlink,
                          st_uid=stx.stx_uid, st_gid=stx.stx_gid,
                          st_rdev=stx.stx_rdev, st_size=stx.stx_size,
                          st_blksize=stx.stx_blksize,
                          st_blocks=stx.stx_blocks,
                          st_atime=datetime.fromtimestamp(stx.stx_atime.tv_sec),
                          st_mtime=datetime.fromtimestamp(stx.stx_mtime.tv_sec),
                          st_ctime=datetime.fromtimestamp(stx.stx_ctime.tv_sec))
    
    def statx(self, path, mask, flag):
        """
        Get a file's extended statistics and attributes.

        :param path: the file or directory to get the statistics of.
        :param mask: want bitfield of CEPH_STATX_* flags showing designed attributes.
        :param flag: bitfield that can be used to set AT_* modifier flags (AT_STATX_SYNC_AS_STAT, AT_STATX_FORCE_SYNC, AT_STATX_DONT_SYNC and AT_SYMLINK_NOFOLLOW)
        """

        self.require_state("mounted")
        path = cstr(path, 'path')
        if not isinstance(mask, int):
            raise TypeError('flag must be a int')
        if not isinstance(flag, int):
            raise TypeError('flag must be a int')

        cdef:
            char* _path = path
            statx stx
            int _mask = mask
            int _flag = flag
            dict_result = dict()

        with nogil:
            ret = ceph_statx(self.cluster, _path, &stx, _mask, _flag)
        if ret < 0:
            raise make_ex(ret, "error in stat: %s" % path)

        if (_mask & CEPH_STATX_MODE):
            dict_result["mode"] = stx.stx_mode
        if (_mask & CEPH_STATX_NLINK):
            dict_result["nlink"] = stx.stx_nlink
        if (_mask & CEPH_STATX_UID):
            dict_result["uid"] = stx.stx_uid
        if (_mask & CEPH_STATX_GID):
            dict_result["gid"] = stx.stx_gid
        if (_mask & CEPH_STATX_RDEV):
            dict_result["rdev"] = stx.stx_rdev
        if (_mask & CEPH_STATX_ATIME):
            dict_result["atime"] = datetime.fromtimestamp(stx.stx_atime.tv_sec)
        if (_mask & CEPH_STATX_MTIME):
            dict_result["mtime"] = datetime.fromtimestamp(stx.stx_mtime.tv_sec)
        if (_mask & CEPH_STATX_CTIME):
            dict_result["ctime"] = datetime.fromtimestamp(stx.stx_ctime.tv_sec)
        if (_mask & CEPH_STATX_INO):
            dict_result["ino"] = stx.stx_ino
        if (_mask & CEPH_STATX_SIZE):
            dict_result["size"] = stx.stx_size
        if (_mask & CEPH_STATX_BLOCKS):
            dict_result["blocks"] = stx.stx_blocks
        if (_mask & CEPH_STATX_BTIME):
            dict_result["btime"] = datetime.fromtimestamp(stx.stx_btime.tv_sec)
        if (_mask & CEPH_STATX_VERSION):
            dict_result["version"] = stx.stx_version

        return dict_result

    def setattrx(self, path, dict_stx, mask, flags):
        """
        Set a file's attributes.

        :param path: the path to the file/directory to set the attributes of.
        :param mask: a mask of all the CEPH_SETATTR_* values that have been set in the statx struct.
        :param stx: a dict of statx structure that must include attribute values to set on the file.
        :param flags: mask of AT_* flags (only AT_ATTR_NOFOLLOW is respected for now)
        """

        self.require_state("mounted")
        path = cstr(path, 'path')
        if not isinstance(dict_stx, dict):
            raise TypeError('dict_stx must be a dict')
        if not isinstance(mask, int):
            raise TypeError('mask must be a int')
        if not isinstance(flags, int):
            raise TypeError('flags must be a int')

        cdef statx stx

        if (mask & CEPH_SETATTR_MODE):
            stx.stx_mode = dict_stx["mode"]
        if (mask & CEPH_SETATTR_UID):
            stx.stx_uid = dict_stx["uid"]
        if (mask & CEPH_SETATTR_GID):
            stx.stx_gid = dict_stx["gid"]
        if (mask & CEPH_SETATTR_MTIME):
            stx.stx_mtime = to_timespec(dict_stx["mtime"].timestamp())
        if (mask & CEPH_SETATTR_ATIME):
            stx.stx_atime = to_timespec(dict_stx["atime"].timestamp())
        if (mask & CEPH_SETATTR_CTIME):
            stx.stx_ctime = to_timespec(dict_stx["ctime"].timestamp())
        if (mask & CEPH_SETATTR_SIZE):
            stx.stx_size = dict_stx["size"]
        if (mask & CEPH_SETATTR_BTIME):
            stx.stx_btime = to_timespec(dict_stx["btime"].timestamp())

        cdef:
            char* _path = path
            int _mask = mask
            int _flags = flags
            dict_result = dict()

        with nogil:
            ret = ceph_setattrx(self.cluster, _path, &stx, _mask, _flags)
        if ret < 0:
            raise make_ex(ret, "error in setattrx: %s" % path)

    def fsetattrx(self, fd, dict_stx, mask):
        """
        Set a file's attributes.

        :param path: the path to the file/directory to set the attributes of.
        :param mask: a mask of all the CEPH_SETATTR_* values that have been set in the statx struct.
        :param stx: a dict of statx structure that must include attribute values to set on the file.
        """

        self.require_state("mounted")
        if not isinstance(fd, int):
            raise TypeError('fd must be a int')
        if not isinstance(dict_stx, dict):
            raise TypeError('dict_stx must be a dict')
        if not isinstance(mask, int):
            raise TypeError('mask must be a int')

        cdef statx stx

        if (mask & CEPH_SETATTR_MODE):
            stx.stx_mode = dict_stx["mode"]
        if (mask & CEPH_SETATTR_UID):
            stx.stx_uid = dict_stx["uid"]
        if (mask & CEPH_SETATTR_GID):
            stx.stx_gid = dict_stx["gid"]
        if (mask & CEPH_SETATTR_MTIME):
            stx.stx_mtime = to_timespec(dict_stx["mtime"].timestamp())
        if (mask & CEPH_SETATTR_ATIME):
            stx.stx_atime = to_timespec(dict_stx["atime"].timestamp())
        if (mask & CEPH_SETATTR_CTIME):
            stx.stx_ctime = to_timespec(dict_stx["ctime"].timestamp())
        if (mask & CEPH_SETATTR_SIZE):
            stx.stx_size = dict_stx["size"]
        if (mask & CEPH_SETATTR_BTIME):
            stx.stx_btime = to_timespec(dict_stx["btime"].timestamp())

        cdef:
            int _fd = fd
            int _mask = mask
            dict_result = dict()

        with nogil:
            ret = ceph_fsetattrx(self.cluster, _fd, &stx, _mask)
        if ret < 0:
            raise make_ex(ret, "error in fsetattrx")

    def symlink(self, existing, newname):
        """
        Creates a symbolic link.
       
        :param existing: the path to the existing file/directory to link to.
        :param newname: the path to the new file/directory to link from.
        """
        self.require_state("mounted")
        existing = cstr(existing, 'existing')
        newname = cstr(newname, 'newname')
        cdef:
            char* _existing = existing
            char* _newname = newname

        with nogil:
            ret = ceph_symlink(self.cluster, _existing, _newname)
        if ret < 0:
            raise make_ex(ret, "error in symlink")
    
    def link(self, existing, newname):
        """
        Create a link.
        
        :param existing: the path to the existing file/directory to link to.
        :param newname: the path to the new file/directory to link from.
        """

        self.require_state("mounted")
        existing = cstr(existing, 'existing')
        newname = cstr(newname, 'newname')
        cdef:
            char* _existing = existing
            char* _newname = newname
        
        with nogil:
            ret = ceph_link(self.cluster, _existing, _newname)
        if ret < 0:
            raise make_ex(ret, "error in link")    
    
    def readlink(self, path, size):
        """
        Read a symbolic link.
      
        :param path: the path to the symlink to read
        :param size: the length of the buffer
        :rtype buf: buffer to hold the path of the file that the symlink points to.
        """
        self.require_state("mounted")
        path = cstr(path, 'path')

        cdef:
            char* _path = path
            int64_t _size = size
            char *buf = NULL

        try:
            buf = <char *>realloc_chk(buf, _size)
            with nogil:
                ret = ceph_readlink(self.cluster, _path, buf, _size)
            if ret < 0:
                raise make_ex(ret, "error in readlink")
            return buf[:ret]
        finally:
            free(buf)

    def unlink(self, path):
        """
        Removes a file, link, or symbolic link.  If the file/link has multiple links to it, the
        file will not disappear from the namespace until all references to it are removed.
        
        :param path: the path of the file or link to unlink.
        """
        self.require_state("mounted")
        path = cstr(path, 'path')
        cdef char* _path = path
        with nogil:
            ret = ceph_unlink(self.cluster, _path)
        if ret < 0:
            raise make_ex(ret, "error in unlink: {}".format(path.decode('utf-8')))

    def rename(self, src, dst):
        """
        Rename a file or directory.
        
        :param src: the path to the existing file or directory.
        :param dst: the new name of the file or directory.
        """
        
        self.require_state("mounted")

        src = cstr(src, 'source')
        dst = cstr(dst, 'destination')

        cdef:
            char* _src = src
            char* _dst = dst

        with nogil:
            ret = ceph_rename(self.cluster, _src, _dst)
        if ret < 0:
            raise make_ex(ret, "error in rename {} to {}".format(src.decode(
                          'utf-8'), dst.decode('utf-8')))

    def mds_command(self, mds_spec, args, input_data):
        """
        :return 3-tuple of output status int, output status string, output data
        """
        mds_spec = cstr(mds_spec, 'mds_spec')
        args = cstr(args, 'args')
        input_data = cstr(input_data, 'input_data')

        cdef:
            char *_mds_spec = opt_str(mds_spec)
            char **_cmd = to_bytes_array([args])
            size_t _cmdlen = 1

            char *_inbuf = input_data
            size_t _inbuf_len = len(input_data)

            char *_outbuf = NULL
            size_t _outbuf_len = 0
            char *_outs = NULL
            size_t _outs_len = 0

        try:
            with nogil:
                ret = ceph_mds_command(self.cluster, _mds_spec,
                                       <const char **>_cmd, _cmdlen,
                                       <const char*>_inbuf, _inbuf_len,
                                       &_outbuf, &_outbuf_len,
                                       &_outs, &_outs_len)
            my_outs = decode_cstr(_outs[:_outs_len])
            my_outbuf = _outbuf[:_outbuf_len]
            if _outs_len:
                ceph_buffer_free(_outs)
            if _outbuf_len:
                ceph_buffer_free(_outbuf)
            return (ret, my_outbuf, my_outs)
        finally:
            free(_cmd)

    def umask(self, mode) :
        self.require_state("mounted")
        cdef:
            mode_t _mode = mode
        with nogil:
            ret = ceph_umask(self.cluster, _mode)
        if ret < 0:
            raise make_ex(ret, "error in umask")
        return ret

    def lseek(self, fd, offset, whence):
        """
        Set the file's current position.
 
        :param fd: the file descriptor of the open file to read from.
        :param offset: the offset in the file to read from.  If this value is negative, the
                       function reads from the current offset of the file descriptor.
        :param whence: the flag to indicate what type of seeking to performs:SEEK_SET, SEEK_CUR, SEEK_END
        """     
        self.require_state("mounted")
        if not isinstance(fd, int):
            raise TypeError('fd must be an int')
        if not isinstance(offset, int):
            raise TypeError('offset must be an int')
        if not isinstance(whence, int):
            raise TypeError('whence must be an int')

        cdef:
            int _fd = fd
            int64_t _offset = offset
            int64_t _whence = whence

        with nogil:
            ret = ceph_lseek(self.cluster, _fd, _offset, _whence)

        if ret < 0:
            raise make_ex(ret, "error in lseek")

        return ret      

    def utime(self, path, times=None):
        """
        Set access and modification time for path

        :param path: file path for which timestamps have to be changed
        :param times: if times is not None, it must be a tuple (atime, mtime)
        """

        self.require_state("mounted")
        path = cstr(path, 'path')
        if times:
            if not isinstance(times, tuple):
                raise TypeError('times must be a tuple')
            if not isinstance(times[0], int):
                raise TypeError('atime must be an int')
            if not isinstance(times[1], int):
                raise TypeError('mtime must be an int')
        actime = modtime = int(time.time())
        if times:
            actime = times[0]
            modtime = times[1]

        cdef:
            char *pth = path
            utimbuf buf = utimbuf(actime, modtime)
        with nogil:
            ret = ceph_utime(self.cluster, pth, &buf)
        if ret < 0:
            raise make_ex(ret, "error in utime {}".format(path.decode('utf-8')))

    def futime(self, fd, times=None):
        """
        Set access and modification time for a file pointed by descriptor

        :param fd: file descriptor of the open file
        :param times: if times is not None, it must be a tuple (atime, mtime)
        """

        self.require_state("mounted")
        if not isinstance(fd, int):
            raise TypeError('fd must be an int')
        if times:
            if not isinstance(times, tuple):
                raise TypeError('times must be a tuple')
            if not isinstance(times[0], int):
                raise TypeError('atime must be an int')
            if not isinstance(times[1], int):
                raise TypeError('mtime must be an int')
        actime = modtime = int(time.time())
        if times:
            actime = times[0]
            modtime = times[1]

        cdef:
            int _fd = fd
            utimbuf buf = utimbuf(actime, modtime)
        with nogil:
            ret = ceph_futime(self.cluster, _fd, &buf)
        if ret < 0:
            raise make_ex(ret, "error in futime")

    def utimes(self, path, times=None, follow_symlink=True):
        """
        Set access and modification time for path

        :param path: file path for which timestamps have to be changed
        :param times: if times is not None, it must be a tuple (atime, mtime)
        :param follow_symlink: perform the operation on the target file if @path
                               is a symbolic link (default)
        """

        self.require_state("mounted")
        path = cstr(path, 'path')
        if times:
            if not isinstance(times, tuple):
                raise TypeError('times must be a tuple')
            if not isinstance(times[0], (int, float)):
                raise TypeError('atime must be an int or a float')
            if not isinstance(times[1], (int, float)):
                raise TypeError('mtime must be an int or a float')
        actime = modtime = time.time()
        if times:
            actime = float(times[0])
            modtime = float(times[1])

        cdef:
            char *pth = path
            timeval *buf = [to_timeval(actime), to_timeval(modtime)]
        if follow_symlink:
            with nogil:
                ret = ceph_utimes(self.cluster, pth, buf)
        else:
            with nogil:
                ret = ceph_lutimes(self.cluster, pth, buf)
        if ret < 0:
            raise make_ex(ret, "error in utimes {}".format(path.decode('utf-8')))

    def lutimes(self, path, times=None):
        """
        Set access and modification time for a file. If the file is a symbolic
        link do not follow to the target.

        :param path: file path for which timestamps have to be changed
        :param times: if times is not None, it must be a tuple (atime, mtime)
        """
        self.utimes(path, times=times, follow_symlink=False)

    def futimes(self, fd, times=None):
        """
        Set access and modification time for a file pointer by descriptor

        :param fd: file descriptor of the open file
        :param times: if times is not None, it must be a tuple (atime, mtime)
        """

        self.require_state("mounted")
        if not isinstance(fd, int):
            raise TypeError('fd must be an int')
        if times:
            if not isinstance(times, tuple):
                raise TypeError('times must be a tuple')
            if not isinstance(times[0], (int, float)):
                raise TypeError('atime must be an int or a float')
            if not isinstance(times[1], (int, float)):
                raise TypeError('mtime must be an int or a float')
        actime = modtime = time.time()
        if times:
            actime = float(times[0])
            modtime = float(times[1])

        cdef:
            int _fd = fd
            timeval *buf = [to_timeval(actime), to_timeval(modtime)]
        with nogil:
                ret = ceph_futimes(self.cluster, _fd, buf)
        if ret < 0:
            raise make_ex(ret, "error in futimes")

    def futimens(self, fd, times=None):
        """
        Set access and modification time for a file pointer by descriptor

        :param fd: file descriptor of the open file
        :param times: if times is not None, it must be a tuple (atime, mtime)
        """

        self.require_state("mounted")
        if not isinstance(fd, int):
            raise TypeError('fd must be an int')
        if times:
            if not isinstance(times, tuple):
                raise TypeError('times must be a tuple')
            if not isinstance(times[0], (int, float)):
                raise TypeError('atime must be an int or a float')
            if not isinstance(times[1], (int, float)):
                raise TypeError('mtime must be an int or a float')
        actime = modtime = time.time()
        if times:
            actime = float(times[0])
            modtime = float(times[1])

        cdef:
            int _fd = fd
            timespec *buf = [to_timespec(actime), to_timespec(modtime)]
        with nogil:
                ret = ceph_futimens(self.cluster, _fd, buf)
        if ret < 0:
            raise make_ex(ret, "error in futimens")

    def get_file_replication(self, fd):
        """
        Get the file replication information from an open file descriptor.

        :param fd : the open file descriptor referring to the file to get
                    the replication information of.
        """
        self.require_state("mounted")
        if not isinstance(fd, int):
            raise TypeError('fd must be an int')

        cdef:
            int _fd = fd

        with nogil:
            ret = ceph_get_file_replication(self.cluster, _fd)
        if ret < 0:
            raise make_ex(ret, "error in get_file_replication")

        return ret

    def get_path_replication(self, path):
        """
        Get the file replication information given the path.

        :param path: the path of the file/directory to get the replication information of.
        """
        self.require_state("mounted")
        path = cstr(path, 'path')

        cdef:
            char* _path = path

        with nogil:
            ret = ceph_get_path_replication(self.cluster, _path)
        if ret < 0:
            raise make_ex(ret, "error in get_path_replication")

        return ret

    def get_pool_id(self, pool_name):
        """
        Get the id of the named pool.

        :param pool_name: the name of the pool.
        """

        self.require_state("mounted")
        pool_name = cstr(pool_name, 'pool_name')

        cdef:
            char* _pool_name = pool_name

        with nogil:
            ret = ceph_get_pool_id(self.cluster, _pool_name)
        if ret < 0:
            raise make_ex(ret, "error in get_pool_id")

        return ret

    def get_pool_replication(self, pool_id):
        """
        Get the pool replication factor.

        :param pool_id: the pool id to look up
        """

        self.require_state("mounted")
        if not isinstance(pool_id, int):
            raise TypeError('pool_id must be an int')

        cdef:
            int _pool_id = pool_id

        with nogil:
            ret = ceph_get_pool_replication(self.cluster, _pool_id)
        if ret < 0:
            raise make_ex(ret, "error in get_pool_replication")

        return ret

    def debug_get_fd_caps(self, fd):
        """
        Get the capabilities currently issued to the client given the fd.

        :param fd: the file descriptor to get issued
        """

        self.require_state("mounted")
        if not isinstance(fd, int):
            raise TypeError('fd must be an int')

        cdef:
            int _fd = fd

        with nogil:
            ret = ceph_debug_get_fd_caps(self.cluster, _fd)
        if ret < 0:
            raise make_ex(ret, "error in debug_get_fd_caps")

        return ret

    def debug_get_file_caps(self, path):
        """
        Get the capabilities currently issued to the client given the path.

        :param path: the path of the file/directory to get the capabilities of.
        """

        self.require_state("mounted")
        path = cstr(path, 'path')

        cdef:
            char* _path = path

        with nogil:
            ret = ceph_debug_get_file_caps(self.cluster, _path)
        if ret < 0:
            raise make_ex(ret, "error in debug_get_file_caps")

        return ret

    def get_cap_return_timeout(self):
        """
        Get the amount of time that the client has to return caps

        In the event that a client does not return its caps, the MDS may blocklist
        it after this timeout. Applications should check this value and ensure
        that they set the delegation timeout to a value lower than this.
        """

        self.require_state("mounted")

        with nogil:
            ret = ceph_get_cap_return_timeout(self.cluster)
        if ret < 0:
            raise make_ex(ret, "error in get_cap_return_timeout")

        return ret

    def set_uuid(self, uuid):
        """
        Set ceph client uuid. Must be called before mount.

        :param uuid: the uuid to set
        """

        uuid = cstr(uuid, 'uuid')

        cdef:
            char* _uuid = uuid

        with nogil:
            ceph_set_uuid(self.cluster, _uuid)

    def set_session_timeout(self, timeout):
        """
        Set ceph client session timeout. Must be called before mount.

        :param timeout: the timeout to set
        """

        if not isinstance(timeout, int):
            raise TypeError('timeout must be an int')

        cdef:
            int _timeout = timeout

        with nogil:
            ceph_set_session_timeout(self.cluster, _timeout)

    def get_layout(self, fd):
        """
        Set ceph client session timeout. Must be called before mount.

        :param fd: file descriptor of the file/directory for which to get the layout
        """

        if not isinstance(fd, int):
            raise TypeError('fd must be an int')

        cdef:
            int _fd = fd
            int stripe_unit
            int stripe_count
            int object_size
            int pool_id
            char *buf = NULL
            int buflen = 256
            dict_result = dict()

        with nogil:
            ret = ceph_get_file_layout(self.cluster, _fd, &stripe_unit, &stripe_count, &object_size, &pool_id)
        if ret < 0:
            raise make_ex(stripe_unit, "error in get_file_layout")
        dict_result["stripe_unit"] = stripe_unit
        dict_result["stripe_count"] = stripe_count
        dict_result["object_size"] = object_size
        dict_result["pool_id"] = pool_id

        try:
            while True:
                buf = <char *>realloc_chk(buf, buflen)
                with nogil:
                    ret = ceph_get_file_pool_name(self.cluster, _fd, buf, buflen)
                if ret > 0:
                    dict_result["pool_name"] = decode_cstr(buf)
                    return dict_result
                elif ret == -CEPHFS_ERANGE:
                    buflen = buflen * 2
                else:
                    raise make_ex(ret, "error in get_file_pool_name")
        finally:
           free(buf)


    def get_default_pool(self):
        """
        Get the default pool name and id of cephfs. This returns dict{pool_name, pool_id}.
        """

        cdef:
            char *buf = NULL
            int buflen = 256
            dict_result = dict()

        try:
            while True:
                buf = <char *>realloc_chk(buf, buflen)
                with nogil:
                    ret = ceph_get_default_data_pool_name(self.cluster, buf, buflen)
                if ret > 0:
                    dict_result["pool_name"] = decode_cstr(buf)
                    break
                elif ret == -CEPHFS_ERANGE:
                    buflen = buflen * 2
                else:
                    raise make_ex(ret, "error in get_default_data_pool_name")

            with nogil:
                ret = ceph_get_pool_id(self.cluster, buf)
            if ret < 0:
                raise make_ex(ret, "error in get_pool_id")
            dict_result["pool_id"] = ret
            return dict_result

        finally:
           free(buf)