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
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
|
# cython: embedsignature=True
"""
This module is a thin wrapper around librbd.
It currently provides all the synchronous methods of librbd that do
not use callbacks.
Error codes from librbd are turned into exceptions that subclass
:class:`Error`. Almost all methods may raise :class:`Error`
(the base class of all rbd exceptions), :class:`PermissionError`
and :class:`IOError`, in addition to those documented for the
method.
"""
# Copyright 2011 Josh Durgin
# Copyright 2015 Hector Martin <marcan@marcan.st>
import cython
import json
import sys
from cpython cimport PyObject, ref, exc
from libc cimport errno
from libc.stdint cimport *
from libc.stdlib cimport realloc, free
from libc.string cimport strdup
try:
from collections.abc import Iterable
except ImportError:
from collections import Iterable
from datetime import datetime
import errno
from itertools import chain
import time
IF BUILD_DOC:
include "mock_rbd.pxi"
ELSE:
from c_rbd cimport *
cimport rados
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
cdef extern from "<errno.h>" nogil:
enum:
_ECANCELED "ECANCELED"
ECANCELED = _ECANCELED
RBD_FEATURE_LAYERING = _RBD_FEATURE_LAYERING
RBD_FEATURE_STRIPINGV2 = _RBD_FEATURE_STRIPINGV2
RBD_FEATURE_EXCLUSIVE_LOCK = _RBD_FEATURE_EXCLUSIVE_LOCK
RBD_FEATURE_OBJECT_MAP = _RBD_FEATURE_OBJECT_MAP
RBD_FEATURE_FAST_DIFF = _RBD_FEATURE_FAST_DIFF
RBD_FEATURE_DEEP_FLATTEN = _RBD_FEATURE_DEEP_FLATTEN
RBD_FEATURE_JOURNALING = _RBD_FEATURE_JOURNALING
RBD_FEATURE_DATA_POOL = _RBD_FEATURE_DATA_POOL
RBD_FEATURE_OPERATIONS = _RBD_FEATURE_OPERATIONS
RBD_FEATURE_MIGRATING = _RBD_FEATURE_MIGRATING
RBD_FEATURE_NON_PRIMARY = _RBD_FEATURE_NON_PRIMARY
RBD_FEATURES_INCOMPATIBLE = _RBD_FEATURES_INCOMPATIBLE
RBD_FEATURES_RW_INCOMPATIBLE = _RBD_FEATURES_RW_INCOMPATIBLE
RBD_FEATURES_MUTABLE = _RBD_FEATURES_MUTABLE
RBD_FEATURES_SINGLE_CLIENT = _RBD_FEATURES_SINGLE_CLIENT
RBD_FEATURES_ALL = _RBD_FEATURES_ALL
RBD_OPERATION_FEATURE_CLONE_PARENT = _RBD_OPERATION_FEATURE_CLONE_PARENT
RBD_OPERATION_FEATURE_CLONE_CHILD = _RBD_OPERATION_FEATURE_CLONE_CHILD
RBD_OPERATION_FEATURE_GROUP = _RBD_OPERATION_FEATURE_GROUP
RBD_OPERATION_FEATURE_SNAP_TRASH = _RBD_OPERATION_FEATURE_SNAP_TRASH
RBD_FLAG_OBJECT_MAP_INVALID = _RBD_FLAG_OBJECT_MAP_INVALID
RBD_FLAG_FAST_DIFF_INVALID = _RBD_FLAG_FAST_DIFF_INVALID
RBD_MIRROR_MODE_DISABLED = _RBD_MIRROR_MODE_DISABLED
RBD_MIRROR_MODE_IMAGE = _RBD_MIRROR_MODE_IMAGE
RBD_MIRROR_MODE_POOL = _RBD_MIRROR_MODE_POOL
RBD_MIRROR_PEER_DIRECTION_RX = _RBD_MIRROR_PEER_DIRECTION_RX
RBD_MIRROR_PEER_DIRECTION_TX = _RBD_MIRROR_PEER_DIRECTION_TX
RBD_MIRROR_PEER_DIRECTION_RX_TX = _RBD_MIRROR_PEER_DIRECTION_RX_TX
RBD_MIRROR_IMAGE_MODE_JOURNAL = _RBD_MIRROR_IMAGE_MODE_JOURNAL
RBD_MIRROR_IMAGE_MODE_SNAPSHOT = _RBD_MIRROR_IMAGE_MODE_SNAPSHOT
RBD_MIRROR_IMAGE_DISABLING = _RBD_MIRROR_IMAGE_DISABLING
RBD_MIRROR_IMAGE_ENABLED = _RBD_MIRROR_IMAGE_ENABLED
RBD_MIRROR_IMAGE_DISABLED = _RBD_MIRROR_IMAGE_DISABLED
MIRROR_IMAGE_STATUS_STATE_UNKNOWN = _MIRROR_IMAGE_STATUS_STATE_UNKNOWN
MIRROR_IMAGE_STATUS_STATE_ERROR = _MIRROR_IMAGE_STATUS_STATE_ERROR
MIRROR_IMAGE_STATUS_STATE_SYNCING = _MIRROR_IMAGE_STATUS_STATE_SYNCING
MIRROR_IMAGE_STATUS_STATE_STARTING_REPLAY = _MIRROR_IMAGE_STATUS_STATE_STARTING_REPLAY
MIRROR_IMAGE_STATUS_STATE_REPLAYING = _MIRROR_IMAGE_STATUS_STATE_REPLAYING
MIRROR_IMAGE_STATUS_STATE_STOPPING_REPLAY = _MIRROR_IMAGE_STATUS_STATE_STOPPING_REPLAY
MIRROR_IMAGE_STATUS_STATE_STOPPED = _MIRROR_IMAGE_STATUS_STATE_STOPPED
RBD_LOCK_MODE_EXCLUSIVE = _RBD_LOCK_MODE_EXCLUSIVE
RBD_LOCK_MODE_SHARED = _RBD_LOCK_MODE_SHARED
RBD_IMAGE_OPTION_FORMAT = _RBD_IMAGE_OPTION_FORMAT
RBD_IMAGE_OPTION_FEATURES = _RBD_IMAGE_OPTION_FEATURES
RBD_IMAGE_OPTION_ORDER = _RBD_IMAGE_OPTION_ORDER
RBD_IMAGE_OPTION_STRIPE_UNIT = _RBD_IMAGE_OPTION_STRIPE_UNIT
RBD_IMAGE_OPTION_STRIPE_COUNT = _RBD_IMAGE_OPTION_STRIPE_COUNT
RBD_IMAGE_OPTION_DATA_POOL = _RBD_IMAGE_OPTION_DATA_POOL
RBD_SNAP_NAMESPACE_TYPE_USER = _RBD_SNAP_NAMESPACE_TYPE_USER
RBD_SNAP_NAMESPACE_TYPE_GROUP = _RBD_SNAP_NAMESPACE_TYPE_GROUP
RBD_SNAP_NAMESPACE_TYPE_TRASH = _RBD_SNAP_NAMESPACE_TYPE_TRASH
RBD_SNAP_NAMESPACE_TYPE_MIRROR = _RBD_SNAP_NAMESPACE_TYPE_MIRROR
RBD_SNAP_MIRROR_STATE_PRIMARY = _RBD_SNAP_MIRROR_STATE_PRIMARY
RBD_SNAP_MIRROR_STATE_PRIMARY_DEMOTED = _RBD_SNAP_MIRROR_STATE_PRIMARY_DEMOTED
RBD_SNAP_MIRROR_STATE_NON_PRIMARY = _RBD_SNAP_MIRROR_STATE_NON_PRIMARY
RBD_SNAP_MIRROR_STATE_NON_PRIMARY_DEMOTED = _RBD_SNAP_MIRROR_STATE_NON_PRIMARY_DEMOTED
RBD_GROUP_IMAGE_STATE_ATTACHED = _RBD_GROUP_IMAGE_STATE_ATTACHED
RBD_GROUP_IMAGE_STATE_INCOMPLETE = _RBD_GROUP_IMAGE_STATE_INCOMPLETE
RBD_GROUP_SNAP_STATE_INCOMPLETE = _RBD_GROUP_SNAP_STATE_INCOMPLETE
RBD_GROUP_SNAP_STATE_COMPLETE = _RBD_GROUP_SNAP_STATE_COMPLETE
RBD_IMAGE_MIGRATION_STATE_UNKNOWN = _RBD_IMAGE_MIGRATION_STATE_UNKNOWN
RBD_IMAGE_MIGRATION_STATE_ERROR = _RBD_IMAGE_MIGRATION_STATE_ERROR
RBD_IMAGE_MIGRATION_STATE_PREPARING = _RBD_IMAGE_MIGRATION_STATE_PREPARING
RBD_IMAGE_MIGRATION_STATE_PREPARED = _RBD_IMAGE_MIGRATION_STATE_PREPARED
RBD_IMAGE_MIGRATION_STATE_EXECUTING = _RBD_IMAGE_MIGRATION_STATE_EXECUTING
RBD_IMAGE_MIGRATION_STATE_EXECUTED = _RBD_IMAGE_MIGRATION_STATE_EXECUTED
RBD_IMAGE_MIGRATION_STATE_ABORTING = _RBD_IMAGE_MIGRATION_STATE_ABORTING
RBD_CONFIG_SOURCE_CONFIG = _RBD_CONFIG_SOURCE_CONFIG
RBD_CONFIG_SOURCE_POOL = _RBD_CONFIG_SOURCE_POOL
RBD_CONFIG_SOURCE_IMAGE = _RBD_CONFIG_SOURCE_IMAGE
RBD_POOL_STAT_OPTION_IMAGES = _RBD_POOL_STAT_OPTION_IMAGES
RBD_POOL_STAT_OPTION_IMAGE_PROVISIONED_BYTES = _RBD_POOL_STAT_OPTION_IMAGE_PROVISIONED_BYTES
RBD_POOL_STAT_OPTION_IMAGE_MAX_PROVISIONED_BYTES = _RBD_POOL_STAT_OPTION_IMAGE_MAX_PROVISIONED_BYTES
RBD_POOL_STAT_OPTION_IMAGE_SNAPSHOTS = _RBD_POOL_STAT_OPTION_IMAGE_SNAPSHOTS
RBD_POOL_STAT_OPTION_TRASH_IMAGES = _RBD_POOL_STAT_OPTION_TRASH_IMAGES
RBD_POOL_STAT_OPTION_TRASH_PROVISIONED_BYTES = _RBD_POOL_STAT_OPTION_TRASH_PROVISIONED_BYTES
RBD_POOL_STAT_OPTION_TRASH_MAX_PROVISIONED_BYTES = _RBD_POOL_STAT_OPTION_TRASH_MAX_PROVISIONED_BYTES
RBD_POOL_STAT_OPTION_TRASH_SNAPSHOTS = _RBD_POOL_STAT_OPTION_TRASH_SNAPSHOTS
RBD_SNAP_CREATE_SKIP_QUIESCE = _RBD_SNAP_CREATE_SKIP_QUIESCE
RBD_SNAP_CREATE_IGNORE_QUIESCE_ERROR = _RBD_SNAP_CREATE_IGNORE_QUIESCE_ERROR
RBD_SNAP_REMOVE_UNPROTECT = _RBD_SNAP_REMOVE_UNPROTECT
RBD_SNAP_REMOVE_FLATTEN = _RBD_SNAP_REMOVE_FLATTEN
RBD_SNAP_REMOVE_FORCE = _RBD_SNAP_REMOVE_FORCE
RBD_ENCRYPTION_FORMAT_LUKS1 = _RBD_ENCRYPTION_FORMAT_LUKS1
RBD_ENCRYPTION_FORMAT_LUKS2 = _RBD_ENCRYPTION_FORMAT_LUKS2
RBD_ENCRYPTION_ALGORITHM_AES128 = _RBD_ENCRYPTION_ALGORITHM_AES128
RBD_ENCRYPTION_ALGORITHM_AES256 = _RBD_ENCRYPTION_ALGORITHM_AES256
RBD_WRITE_ZEROES_FLAG_THICK_PROVISION = _RBD_WRITE_ZEROES_FLAG_THICK_PROVISION
class Error(Exception):
pass
class OSError(Error):
""" `OSError` class, derived from `Error` """
def __init__(self, message, errno=None):
super(OSError, self).__init__(message)
self.errno = errno
def __str__(self):
msg = super(OSError, self).__str__()
if self.errno is None:
return msg
return '[errno {0}] {1}'.format(self.errno, msg)
def __reduce__(self):
return (self.__class__, (self.message, self.errno))
class PermissionError(OSError):
def __init__(self, message, errno=None):
super(PermissionError, self).__init__(
"RBD permission error (%s)" % message, errno)
class ImageNotFound(OSError):
def __init__(self, message, errno=None):
super(ImageNotFound, self).__init__(
"RBD image not found (%s)" % message, errno)
class ObjectNotFound(OSError):
def __init__(self, message, errno=None):
super(ObjectNotFound, self).__init__(
"RBD object not found (%s)" % message, errno)
class ImageExists(OSError):
def __init__(self, message, errno=None):
super(ImageExists, self).__init__(
"RBD image already exists (%s)" % message, errno)
class ObjectExists(OSError):
def __init__(self, message, errno=None):
super(ObjectExists, self).__init__(
"RBD object already exists (%s)" % message, errno)
class IOError(OSError):
def __init__(self, message, errno=None):
super(IOError, self).__init__(
"RBD I/O error (%s)" % message, errno)
class NoSpace(OSError):
def __init__(self, message, errno=None):
super(NoSpace, self).__init__(
"RBD insufficient space available (%s)" % message, errno)
class IncompleteWriteError(OSError):
def __init__(self, message, errno=None):
super(IncompleteWriteError, self).__init__(
"RBD incomplete write (%s)" % message, errno)
class InvalidArgument(OSError):
def __init__(self, message, errno=None):
super(InvalidArgument, self).__init__(
"RBD invalid argument (%s)" % message, errno)
class LogicError(OSError):
def __init__(self, message, errno=None):
super(LogicError, self).__init__(
"RBD logic error (%s)" % message, errno)
class ReadOnlyImage(OSError):
def __init__(self, message, errno=None):
super(ReadOnlyImage, self).__init__(
"RBD read-only image (%s)" % message, errno)
class ImageBusy(OSError):
def __init__(self, message, errno=None):
super(ImageBusy, self).__init__(
"RBD image is busy (%s)" % message, errno)
class ImageHasSnapshots(OSError):
def __init__(self, message, errno=None):
super(ImageHasSnapshots, self).__init__(
"RBD image has snapshots (%s)" % message, errno)
class FunctionNotSupported(OSError):
def __init__(self, message, errno=None):
super(FunctionNotSupported, self).__init__(
"RBD function not supported (%s)" % message, errno)
class ArgumentOutOfRange(OSError):
def __init__(self, message, errno=None):
super(ArgumentOutOfRange, self).__init__(
"RBD arguments out of range (%s)" % message, errno)
class ConnectionShutdown(OSError):
def __init__(self, message, errno=None):
super(ConnectionShutdown, self).__init__(
"RBD connection was shutdown (%s)" % message, errno)
class Timeout(OSError):
def __init__(self, message, errno=None):
super(Timeout, self).__init__(
"RBD operation timeout (%s)" % message, errno)
class DiskQuotaExceeded(OSError):
def __init__(self, message, errno=None):
super(DiskQuotaExceeded, self).__init__(
"RBD disk quota exceeded (%s)" % message, errno)
class OperationNotSupported(OSError):
def __init__(self, message, errno=None):
super(OperationNotSupported, self).__init__(
"RBD operation not supported (%s)" % message, errno)
class OperationCanceled(OSError):
def __init__(self, message, errno=None):
super(OperationCanceled, self).__init__(
"RBD operation canceled (%s)" % message, errno)
cdef errno_to_exception = {
errno.EPERM : PermissionError,
errno.ENOENT : ImageNotFound,
errno.EIO : IOError,
errno.ENOSPC : NoSpace,
errno.EEXIST : ImageExists,
errno.EINVAL : InvalidArgument,
errno.EROFS : ReadOnlyImage,
errno.EBUSY : ImageBusy,
errno.ENOTEMPTY : ImageHasSnapshots,
errno.ENOSYS : FunctionNotSupported,
errno.EDOM : ArgumentOutOfRange,
errno.ESHUTDOWN : ConnectionShutdown,
errno.ETIMEDOUT : Timeout,
errno.EDQUOT : DiskQuotaExceeded,
errno.EOPNOTSUPP : OperationNotSupported,
ECANCELED : OperationCanceled,
}
cdef group_errno_to_exception = {
errno.EPERM : PermissionError,
errno.ENOENT : ObjectNotFound,
errno.EIO : IOError,
errno.ENOSPC : NoSpace,
errno.EEXIST : ObjectExists,
errno.EINVAL : InvalidArgument,
errno.EROFS : ReadOnlyImage,
errno.EBUSY : ImageBusy,
errno.ENOTEMPTY : ImageHasSnapshots,
errno.ENOSYS : FunctionNotSupported,
errno.EDOM : ArgumentOutOfRange,
errno.ESHUTDOWN : ConnectionShutdown,
errno.ETIMEDOUT : Timeout,
errno.EDQUOT : DiskQuotaExceeded,
errno.EOPNOTSUPP : OperationNotSupported,
ECANCELED : OperationCanceled,
}
cdef make_ex(ret, msg, exception_map=errno_to_exception):
"""
Translate a librbd 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 exception_map:
return exception_map[ret](msg, errno=ret)
else:
return OSError(msg, errno=ret)
IF BUILD_DOC:
cdef rados_t convert_rados(rados) nogil:
return <rados_t>0
cdef rados_ioctx_t convert_ioctx(ioctx) nogil:
return <rados_ioctx_t>0
ELSE:
cdef rados_t convert_rados(rados.Rados rados) except? NULL:
return <rados_t>rados.cluster
cdef rados_ioctx_t convert_ioctx(rados.Ioctx ioctx) except? NULL:
return <rados_ioctx_t>ioctx.io
cdef int progress_callback(uint64_t offset, uint64_t total, void* ptr) with gil:
return (<object>ptr)(offset, total)
cdef int no_op_progress_callback(uint64_t offset, uint64_t total, void* ptr):
return 0
def cstr(val, name, encoding="utf-8", opt=False):
"""
Create a byte string from a Python string
:param basestring val: Python string
:param str name: Name of the string parameter, for exceptions
:param str encoding: Encoding to use
:param bool opt: If True, None is allowed
:rtype: bytes
:raises: :class:`InvalidArgument`
"""
if opt and val is None:
return None
if isinstance(val, bytes):
return val
elif isinstance(val, str):
return val.encode(encoding)
else:
raise InvalidArgument('%s must be a string' % name)
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 char* opt_str(s) except? NULL:
if s is None:
return NULL
return s
cdef void* realloc_chk(void* ptr, size_t size) except NULL:
cdef void *ret = realloc(ptr, size)
if ret == NULL:
raise MemoryError("realloc failed")
return ret
RBD_MIRROR_PEER_ATTRIBUTE_NAME_MON_HOST = decode_cstr(_RBD_MIRROR_PEER_ATTRIBUTE_NAME_MON_HOST)
RBD_MIRROR_PEER_ATTRIBUTE_NAME_KEY = decode_cstr(_RBD_MIRROR_PEER_ATTRIBUTE_NAME_KEY)
cdef class Completion
cdef void __aio_complete_cb(rbd_completion_t completion, void *args) with gil:
"""
Callback to oncomplete() for asynchronous operations
"""
cdef Completion cb = <Completion>args
cb._complete()
cdef class Completion(object):
"""completion object"""
cdef:
object image
object oncomplete
rbd_completion_t rbd_comp
PyObject* buf
bint persisted
object exc_info
def __cinit__(self, image, object oncomplete):
self.oncomplete = oncomplete
self.image = image
self.persisted = False
def is_complete(self):
"""
Has an asynchronous operation completed?
This does not imply that the callback has finished.
:returns: True if the operation is completed
"""
with nogil:
ret = rbd_aio_is_complete(self.rbd_comp)
return ret == 1
def wait_for_complete_and_cb(self):
"""
Wait for an asynchronous operation to complete
This method waits for the callback to execute, if one was provided.
It will also re-raise any exceptions raised by the callback. You
should call this to "reap" asynchronous completions and ensure that
any exceptions in the callbacks are handled, as an exception internal
to this module may have occurred.
"""
with nogil:
rbd_aio_wait_for_complete(self.rbd_comp)
if self.exc_info:
raise self.exc_info[0], self.exc_info[1], self.exc_info[2]
def get_return_value(self):
"""
Get the return value of an asychronous operation
The return value is set when the operation is complete.
:returns: int - return value of the operation
"""
with nogil:
ret = rbd_aio_get_return_value(self.rbd_comp)
return ret
def __dealloc__(self):
"""
Release a completion
This is automatically called when the completion object is freed.
"""
ref.Py_XDECREF(self.buf)
self.buf = NULL
if self.rbd_comp != NULL:
with nogil:
rbd_aio_release(self.rbd_comp)
self.rbd_comp = NULL
cdef void _complete(self):
try:
self.__unpersist()
if self.oncomplete:
self.oncomplete(self)
# In the event that something raises an exception during the next 2
# lines of code, we will not be able to catch it, and this may result
# in the app not noticing a failed callback. However, this should only
# happen in extreme circumstances (OOM, etc.). KeyboardInterrupt
# should not be a problem because the callback thread from librbd
# ought to have SIGINT blocked.
except:
self.exc_info = sys.exc_info()
cdef __persist(self):
if self.oncomplete is not None and not self.persisted:
# Increment our own reference count to make sure the completion
# is not freed until the callback is called. The completion is
# allowed to be freed if there is no callback.
ref.Py_INCREF(self)
self.persisted = True
cdef __unpersist(self):
if self.persisted:
ref.Py_DECREF(self)
self.persisted = False
class RBD(object):
"""
This class wraps librbd CRUD functions.
"""
def version(self):
"""
Get the version number of the ``librbd`` C library.
:returns: a tuple of ``(major, minor, extra)`` components of the
librbd version
"""
cdef int major = 0
cdef int minor = 0
cdef int extra = 0
rbd_version(&major, &minor, &extra)
return (major, minor, extra)
def create(self, ioctx, name, size, order=None, old_format=False,
features=None, stripe_unit=None, stripe_count=None,
data_pool=None):
"""
Create an rbd image.
:param ioctx: the context in which to create the image
:type ioctx: :class:`rados.Ioctx`
:param name: what the image is called
:type name: str
:param size: how big the image is in bytes
:type size: int
:param order: the image is split into (2**order) byte objects
:type order: int
:param old_format: whether to create an old-style image that
is accessible by old clients, but can't
use more advanced features like layering.
:type old_format: bool
:param features: bitmask of features to enable
:type features: int
:param stripe_unit: stripe unit in bytes (default None to let librbd decide)
:type stripe_unit: int
:param stripe_count: objects to stripe over before looping
:type stripe_count: int
:param data_pool: optional separate pool for data blocks
:type data_pool: str
:raises: :class:`ImageExists`
:raises: :class:`TypeError`
:raises: :class:`InvalidArgument`
:raises: :class:`FunctionNotSupported`
"""
name = cstr(name, 'name')
data_pool = cstr(data_pool, 'data_pool', opt=True)
cdef:
rados_ioctx_t _ioctx = convert_ioctx(ioctx)
char *_name = name
uint64_t _size = size
int _order = 0
rbd_image_options_t opts
if order is not None:
_order = order
if old_format:
if (features or
((stripe_unit is not None) and stripe_unit != 0) or
((stripe_count is not None) and stripe_count != 0) or
data_pool):
raise InvalidArgument('format 1 images do not support feature '
'masks, non-default striping, nor data '
'pool')
with nogil:
ret = rbd_create(_ioctx, _name, _size, &_order)
else:
rbd_image_options_create(&opts)
try:
rbd_image_options_set_uint64(opts, RBD_IMAGE_OPTION_FORMAT,
1 if old_format else 2)
if features is not None:
rbd_image_options_set_uint64(opts,
RBD_IMAGE_OPTION_FEATURES,
features)
if order is not None:
rbd_image_options_set_uint64(opts, RBD_IMAGE_OPTION_ORDER,
_order)
if stripe_unit is not None:
rbd_image_options_set_uint64(opts, RBD_IMAGE_OPTION_STRIPE_UNIT,
stripe_unit)
if stripe_count is not None:
rbd_image_options_set_uint64(opts,
RBD_IMAGE_OPTION_STRIPE_COUNT,
stripe_count)
if data_pool is not None:
rbd_image_options_set_string(opts,
RBD_IMAGE_OPTION_DATA_POOL,
data_pool)
with nogil:
ret = rbd_create4(_ioctx, _name, _size, opts)
finally:
rbd_image_options_destroy(opts)
if ret < 0:
raise make_ex(ret, 'error creating image')
def clone(self, p_ioctx, p_name, p_snapname, c_ioctx, c_name,
features=None, order=None, stripe_unit=None, stripe_count=None,
data_pool=None):
"""
Clone a parent rbd snapshot into a COW sparse child.
:param p_ioctx: the parent context that represents the parent snap
:type ioctx: :class:`rados.Ioctx`
:param p_name: the parent image name
:type name: str
:param p_snapname: the parent image snapshot name
:type name: str
:param c_ioctx: the child context that represents the new clone
:type ioctx: :class:`rados.Ioctx`
:param c_name: the clone (child) name
:type name: str
:param features: bitmask of features to enable; if set, must include layering
:type features: int
:param order: the image is split into (2**order) byte objects
:type order: int
:param stripe_unit: stripe unit in bytes (default None to let librbd decide)
:type stripe_unit: int
:param stripe_count: objects to stripe over before looping
:type stripe_count: int
:param data_pool: optional separate pool for data blocks
:type data_pool: str
:raises: :class:`TypeError`
:raises: :class:`InvalidArgument`
:raises: :class:`ImageExists`
:raises: :class:`FunctionNotSupported`
:raises: :class:`ArgumentOutOfRange`
"""
p_snapname = cstr(p_snapname, 'p_snapname')
p_name = cstr(p_name, 'p_name')
c_name = cstr(c_name, 'c_name')
data_pool = cstr(data_pool, 'data_pool', opt=True)
cdef:
rados_ioctx_t _p_ioctx = convert_ioctx(p_ioctx)
rados_ioctx_t _c_ioctx = convert_ioctx(c_ioctx)
char *_p_name = p_name
char *_p_snapname = p_snapname
char *_c_name = c_name
rbd_image_options_t opts
rbd_image_options_create(&opts)
try:
if features is not None:
rbd_image_options_set_uint64(opts, RBD_IMAGE_OPTION_FEATURES,
features)
if order is not None:
rbd_image_options_set_uint64(opts, RBD_IMAGE_OPTION_ORDER,
order)
if stripe_unit is not None:
rbd_image_options_set_uint64(opts, RBD_IMAGE_OPTION_STRIPE_UNIT,
stripe_unit)
if stripe_count is not None:
rbd_image_options_set_uint64(opts, RBD_IMAGE_OPTION_STRIPE_COUNT,
stripe_count)
if data_pool is not None:
rbd_image_options_set_string(opts, RBD_IMAGE_OPTION_DATA_POOL,
data_pool)
with nogil:
ret = rbd_clone3(_p_ioctx, _p_name, _p_snapname,
_c_ioctx, _c_name, opts)
finally:
rbd_image_options_destroy(opts)
if ret < 0:
raise make_ex(ret, 'error creating clone')
def list(self, ioctx):
"""
List image names.
:param ioctx: determines which RADOS pool is read
:type ioctx: :class:`rados.Ioctx`
:returns: list -- a list of image names
"""
cdef:
rados_ioctx_t _ioctx = convert_ioctx(ioctx)
size_t size = 512
char *c_names = NULL
try:
while True:
c_names = <char *>realloc_chk(c_names, size)
with nogil:
ret = rbd_list(_ioctx, c_names, &size)
if ret >= 0:
break
elif ret != -errno.ERANGE:
raise make_ex(ret, 'error listing images')
return [decode_cstr(name) for name in c_names[:ret].split(b'\0')
if name]
finally:
free(c_names)
def list2(self, ioctx):
"""
Iterate over the images in the pool.
:param ioctx: determines which RADOS pool the image is in
:type ioctx: :class:`rados.Ioctx`
:returns: :class:`ImageIterator`
"""
return ImageIterator(ioctx)
def remove(self, ioctx, name, on_progress=None):
"""
Delete an RBD image. This may take a long time, since it does
not return until every object that comprises the image has
been deleted. Note that all snapshots must be deleted before
the image can be removed. If there are snapshots left,
:class:`ImageHasSnapshots` is raised. If the image is still
open, or the watch from a crashed client has not expired,
:class:`ImageBusy` is raised.
:param ioctx: determines which RADOS pool the image is in
:type ioctx: :class:`rados.Ioctx`
:param name: the name of the image to remove
:type name: str
:param on_progress: optional progress callback function
:type on_progress: callback function
:raises: :class:`ImageNotFound`, :class:`ImageBusy`,
:class:`ImageHasSnapshots`
"""
name = cstr(name, 'name')
cdef:
rados_ioctx_t _ioctx = convert_ioctx(ioctx)
char *_name = name
librbd_progress_fn_t _prog_cb = &no_op_progress_callback
void *_prog_arg = NULL
if on_progress:
_prog_cb = &progress_callback
_prog_arg = <void *>on_progress
with nogil:
ret = rbd_remove_with_progress(_ioctx, _name, _prog_cb, _prog_arg)
if ret != 0:
raise make_ex(ret, 'error removing image')
def rename(self, ioctx, src, dest):
"""
Rename an RBD image.
:param ioctx: determines which RADOS pool the image is in
:type ioctx: :class:`rados.Ioctx`
:param src: the current name of the image
:type src: str
:param dest: the new name of the image
:type dest: str
:raises: :class:`ImageNotFound`, :class:`ImageExists`
"""
src = cstr(src, 'src')
dest = cstr(dest, 'dest')
cdef:
rados_ioctx_t _ioctx = convert_ioctx(ioctx)
char *_src = src
char *_dest = dest
with nogil:
ret = rbd_rename(_ioctx, _src, _dest)
if ret != 0:
raise make_ex(ret, 'error renaming image')
def trash_move(self, ioctx, name, delay=0):
"""
Move an RBD image to the trash.
:param ioctx: determines which RADOS pool the image is in
:type ioctx: :class:`rados.Ioctx`
:param name: the name of the image to remove
:type name: str
:param delay: time delay in seconds before the image can be deleted
from trash
:type delay: int
:raises: :class:`ImageNotFound`
"""
name = cstr(name, 'name')
cdef:
rados_ioctx_t _ioctx = convert_ioctx(ioctx)
char *_name = name
uint64_t _delay = delay
with nogil:
ret = rbd_trash_move(_ioctx, _name, _delay)
if ret != 0:
raise make_ex(ret, 'error moving image to trash')
def trash_purge(self, ioctx, expire_ts=None, threshold=-1):
"""
Delete RBD images from trash in bulk.
By default it removes images with deferment end time less than now.
The timestamp is configurable, e.g. delete images that have expired a
week ago.
If the threshold is used it deletes images until X% pool usage is met.
:param ioctx: determines which RADOS pool the image is in
:type ioctx: :class:`rados.Ioctx`
:param expire_ts: timestamp for images to be considered as expired (UTC)
:type expire_ts: datetime
:param threshold: percentage of pool usage to be met (0 to 1)
:type threshold: float
"""
if expire_ts:
expire_epoch_ts = time.mktime(expire_ts.timetuple())
else:
expire_epoch_ts = 0
cdef:
rados_ioctx_t _ioctx = convert_ioctx(ioctx)
time_t _expire_ts = expire_epoch_ts
float _threshold = threshold
with nogil:
ret = rbd_trash_purge(_ioctx, _expire_ts, _threshold)
if ret != 0:
raise make_ex(ret, 'error purging images from trash')
def trash_remove(self, ioctx, image_id, force=False, on_progress=None):
"""
Delete an RBD image from trash. If image deferment time has not
expired :class:`PermissionError` is raised.
:param ioctx: determines which RADOS pool the image is in
:type ioctx: :class:`rados.Ioctx`
:param image_id: the id of the image to remove
:type image_id: str
:param force: force remove even if deferment time has not expired
:type force: bool
:param on_progress: optional progress callback function
:type on_progress: callback function
:raises: :class:`ImageNotFound`, :class:`PermissionError`
"""
image_id = cstr(image_id, 'image_id')
cdef:
rados_ioctx_t _ioctx = convert_ioctx(ioctx)
char *_image_id = image_id
int _force = force
librbd_progress_fn_t _prog_cb = &no_op_progress_callback
void *_prog_arg = NULL
if on_progress:
_prog_cb = &progress_callback
_prog_arg = <void *>on_progress
with nogil:
ret = rbd_trash_remove_with_progress(_ioctx, _image_id, _force,
_prog_cb, _prog_arg)
if ret != 0:
raise make_ex(ret, 'error deleting image from trash')
def trash_get(self, ioctx, image_id):
"""
Retrieve RBD image info from trash.
:param ioctx: determines which RADOS pool the image is in
:type ioctx: :class:`rados.Ioctx`
:param image_id: the id of the image to restore
:type image_id: str
:returns: dict - contains the following keys:
* ``id`` (str) - image id
* ``name`` (str) - image name
* ``source`` (str) - source of deletion
* ``deletion_time`` (datetime) - time of deletion
* ``deferment_end_time`` (datetime) - time that an image is allowed
to be removed from trash
:raises: :class:`ImageNotFound`
"""
image_id = cstr(image_id, 'image_id')
cdef:
rados_ioctx_t _ioctx = convert_ioctx(ioctx)
char *_image_id = image_id
rbd_trash_image_info_t c_info
with nogil:
ret = rbd_trash_get(_ioctx, _image_id, &c_info)
if ret != 0:
raise make_ex(ret, 'error retrieving image from trash')
__source_string = ['USER', 'MIRRORING', 'MIGRATION', 'REMOVING']
info = {
'id' : decode_cstr(c_info.id),
'name' : decode_cstr(c_info.name),
'source' : __source_string[c_info.source],
'deletion_time' : datetime.utcfromtimestamp(c_info.deletion_time),
'deferment_end_time' : datetime.utcfromtimestamp(c_info.deferment_end_time)
}
rbd_trash_get_cleanup(&c_info)
return info
def trash_list(self, ioctx):
"""
List all entries from trash.
:param ioctx: determines which RADOS pool the image is in
:type ioctx: :class:`rados.Ioctx`
:returns: :class:`TrashIterator`
"""
return TrashIterator(ioctx)
def trash_restore(self, ioctx, image_id, name):
"""
Restore an RBD image from trash.
:param ioctx: determines which RADOS pool the image is in
:type ioctx: :class:`rados.Ioctx`
:param image_id: the id of the image to restore
:type image_id: str
:param name: the new name of the restored image
:type name: str
:raises: :class:`ImageNotFound`
"""
image_id = cstr(image_id, 'image_id')
name = cstr(name, 'name')
cdef:
rados_ioctx_t _ioctx = convert_ioctx(ioctx)
char *_image_id = image_id
char *_name = name
with nogil:
ret = rbd_trash_restore(_ioctx, _image_id, _name)
if ret != 0:
raise make_ex(ret, 'error restoring image from trash')
def migration_prepare(self, ioctx, image_name, dest_ioctx, dest_image_name,
features=None, order=None, stripe_unit=None, stripe_count=None,
data_pool=None):
"""
Prepare an RBD image migration.
:param ioctx: determines which RADOS pool the image is in
:type ioctx: :class:`rados.Ioctx`
:param image_name: the current name of the image
:type src: str
:param dest_ioctx: determines which pool to migration into
:type dest_ioctx: :class:`rados.Ioctx`
:param dest_image_name: the name of the destination image (may be the same image)
:type dest_image_name: str
:param features: bitmask of features to enable; if set, must include layering
:type features: int
:param order: the image is split into (2**order) byte objects
:type order: int
:param stripe_unit: stripe unit in bytes (default None to let librbd decide)
:type stripe_unit: int
:param stripe_count: objects to stripe over before looping
:type stripe_count: int
:param data_pool: optional separate pool for data blocks
:type data_pool: str
:raises: :class:`TypeError`
:raises: :class:`InvalidArgument`
:raises: :class:`ImageExists`
:raises: :class:`FunctionNotSupported`
:raises: :class:`ArgumentOutOfRange`
"""
image_name = cstr(image_name, 'image_name')
dest_image_name = cstr(dest_image_name, 'dest_image_name')
cdef:
rados_ioctx_t _ioctx = convert_ioctx(ioctx)
char *_image_name = image_name
rados_ioctx_t _dest_ioctx = convert_ioctx(dest_ioctx)
char *_dest_image_name = dest_image_name
rbd_image_options_t opts
rbd_image_options_create(&opts)
try:
if features is not None:
rbd_image_options_set_uint64(opts, RBD_IMAGE_OPTION_FEATURES,
features)
if order is not None:
rbd_image_options_set_uint64(opts, RBD_IMAGE_OPTION_ORDER,
order)
if stripe_unit is not None:
rbd_image_options_set_uint64(opts, RBD_IMAGE_OPTION_STRIPE_UNIT,
stripe_unit)
if stripe_count is not None:
rbd_image_options_set_uint64(opts, RBD_IMAGE_OPTION_STRIPE_COUNT,
stripe_count)
if data_pool is not None:
rbd_image_options_set_string(opts, RBD_IMAGE_OPTION_DATA_POOL,
data_pool)
with nogil:
ret = rbd_migration_prepare(_ioctx, _image_name, _dest_ioctx,
_dest_image_name, opts)
finally:
rbd_image_options_destroy(opts)
if ret < 0:
raise make_ex(ret, 'error migrating image %s' % (image_name))
def migration_prepare_import(self, source_spec, dest_ioctx, dest_image_name,
features=None, order=None, stripe_unit=None,
stripe_count=None, data_pool=None):
"""
Prepare an RBD image migration.
:param source_spec: JSON-encoded source-spec
:type source_spec: str
:param dest_ioctx: determines which pool to migration into
:type dest_ioctx: :class:`rados.Ioctx`
:param dest_image_name: the name of the destination image (may be the same image)
:type dest_image_name: str
:param features: bitmask of features to enable; if set, must include layering
:type features: int
:param order: the image is split into (2**order) byte objects
:type order: int
:param stripe_unit: stripe unit in bytes (default None to let librbd decide)
:type stripe_unit: int
:param stripe_count: objects to stripe over before looping
:type stripe_count: int
:param data_pool: optional separate pool for data blocks
:type data_pool: str
:raises: :class:`TypeError`
:raises: :class:`InvalidArgument`
:raises: :class:`ImageExists`
:raises: :class:`FunctionNotSupported`
:raises: :class:`ArgumentOutOfRange`
"""
source_spec = cstr(source_spec, 'source_spec')
dest_image_name = cstr(dest_image_name, 'dest_image_name')
cdef:
char *_source_spec = source_spec
rados_ioctx_t _dest_ioctx = convert_ioctx(dest_ioctx)
char *_dest_image_name = dest_image_name
rbd_image_options_t opts
rbd_image_options_create(&opts)
try:
if features is not None:
rbd_image_options_set_uint64(opts, RBD_IMAGE_OPTION_FEATURES,
features)
if order is not None:
rbd_image_options_set_uint64(opts, RBD_IMAGE_OPTION_ORDER,
order)
if stripe_unit is not None:
rbd_image_options_set_uint64(opts, RBD_IMAGE_OPTION_STRIPE_UNIT,
stripe_unit)
if stripe_count is not None:
rbd_image_options_set_uint64(opts, RBD_IMAGE_OPTION_STRIPE_COUNT,
stripe_count)
if data_pool is not None:
rbd_image_options_set_string(opts, RBD_IMAGE_OPTION_DATA_POOL,
data_pool)
with nogil:
ret = rbd_migration_prepare_import(_source_spec, _dest_ioctx,
_dest_image_name, opts)
finally:
rbd_image_options_destroy(opts)
if ret < 0:
raise make_ex(ret, 'error migrating image %s' % (source_spec))
def migration_execute(self, ioctx, image_name, on_progress=None):
"""
Execute a prepared RBD image migration.
:param ioctx: determines which RADOS pool the image is in
:type ioctx: :class:`rados.Ioctx`
:param image_name: the name of the image
:type image_name: str
:param on_progress: optional progress callback function
:type on_progress: callback function
:raises: :class:`ImageNotFound`
"""
image_name = cstr(image_name, 'image_name')
cdef:
rados_ioctx_t _ioctx = convert_ioctx(ioctx)
char *_image_name = image_name
librbd_progress_fn_t _prog_cb = &no_op_progress_callback
void *_prog_arg = NULL
if on_progress:
_prog_cb = &progress_callback
_prog_arg = <void *>on_progress
with nogil:
ret = rbd_migration_execute_with_progress(_ioctx, _image_name,
_prog_cb, _prog_arg)
if ret != 0:
raise make_ex(ret, 'error aborting migration')
def migration_commit(self, ioctx, image_name, on_progress=None):
"""
Commit an executed RBD image migration.
:param ioctx: determines which RADOS pool the image is in
:type ioctx: :class:`rados.Ioctx`
:param image_name: the name of the image
:type image_name: str
:param on_progress: optional progress callback function
:type on_progress: callback function
:raises: :class:`ImageNotFound`
"""
image_name = cstr(image_name, 'image_name')
cdef:
rados_ioctx_t _ioctx = convert_ioctx(ioctx)
char *_image_name = image_name
librbd_progress_fn_t _prog_cb = &no_op_progress_callback
void *_prog_arg = NULL
if on_progress:
_prog_cb = &progress_callback
_prog_arg = <void *>on_progress
with nogil:
ret = rbd_migration_commit_with_progress(_ioctx, _image_name,
_prog_cb, _prog_arg)
if ret != 0:
raise make_ex(ret, 'error aborting migration')
def migration_abort(self, ioctx, image_name, on_progress=None):
"""
Cancel a previously started but interrupted migration.
:param ioctx: determines which RADOS pool the image is in
:type ioctx: :class:`rados.Ioctx`
:param image_name: the name of the image
:type image_name: str
:param on_progress: optional progress callback function
:type on_progress: callback function
:raises: :class:`ImageNotFound`
"""
image_name = cstr(image_name, 'image_name')
cdef:
rados_ioctx_t _ioctx = convert_ioctx(ioctx)
char *_image_name = image_name
librbd_progress_fn_t _prog_cb = &no_op_progress_callback
void *_prog_arg = NULL
if on_progress:
_prog_cb = &progress_callback
_prog_arg = <void *>on_progress
with nogil:
ret = rbd_migration_abort_with_progress(_ioctx, _image_name,
_prog_cb, _prog_arg)
if ret != 0:
raise make_ex(ret, 'error aborting migration')
def migration_status(self, ioctx, image_name):
"""
Return RBD image migration status.
:param ioctx: determines which RADOS pool the image is in
:type ioctx: :class:`rados.Ioctx`
:param image_name: the name of the image
:type image_name: str
:returns: dict - contains the following keys:
* ``source_pool_id`` (int) - source image pool id
* ``source_pool_namespace`` (str) - source image pool namespace
* ``source_image_name`` (str) - source image name
* ``source_image_id`` (str) - source image id
* ``dest_pool_id`` (int) - destination image pool id
* ``dest_pool_namespace`` (str) - destination image pool namespace
* ``dest_image_name`` (str) - destination image name
* ``dest_image_id`` (str) - destination image id
* ``state`` (int) - current migration state
* ``state_description`` (str) - migration state description
:raises: :class:`ImageNotFound`
"""
image_name = cstr(image_name, 'image_name')
cdef:
rados_ioctx_t _ioctx = convert_ioctx(ioctx)
char *_image_name = image_name
rbd_image_migration_status_t c_status
with nogil:
ret = rbd_migration_status(_ioctx, _image_name, &c_status,
sizeof(c_status))
if ret != 0:
raise make_ex(ret, 'error getting migration status')
status = {
'source_pool_id' : c_status.source_pool_id,
'source_pool_namespace' : decode_cstr(c_status.source_pool_namespace),
'source_image_name' : decode_cstr(c_status.source_image_name),
'source_image_id' : decode_cstr(c_status.source_image_id),
'dest_pool_id' : c_status.source_pool_id,
'dest_pool_namespace' : decode_cstr(c_status.dest_pool_namespace),
'dest_image_name' : decode_cstr(c_status.dest_image_name),
'dest_image_id' : decode_cstr(c_status.dest_image_id),
'state' : c_status.state,
'state_description' : decode_cstr(c_status.state_description)
}
rbd_migration_status_cleanup(&c_status)
return status
def mirror_site_name_get(self, rados):
"""
Get the local cluster's friendly site name
:param rados: cluster connection
:type rados: :class: rados.Rados
:returns: str - local site name
"""
cdef:
rados_t _rados = convert_rados(rados)
char *_site_name = NULL
size_t _max_size = 512
try:
while True:
_site_name = <char *>realloc_chk(_site_name, _max_size)
with nogil:
ret = rbd_mirror_site_name_get(_rados, _site_name,
&_max_size)
if ret >= 0:
break
elif ret != -errno.ERANGE:
raise make_ex(ret, 'error getting site name')
return decode_cstr(_site_name)
finally:
free(_site_name)
def mirror_site_name_set(self, rados, site_name):
"""
Set the local cluster's friendly site name
:param rados: cluster connection
:type rados: :class: rados.Rados
:param site_name: friendly site name
:type str:
"""
site_name = cstr(site_name, 'site_name')
cdef:
rados_t _rados = convert_rados(rados)
char *_site_name = site_name
with nogil:
ret = rbd_mirror_site_name_set(_rados, _site_name)
if ret != 0:
raise make_ex(ret, 'error setting mirror site name')
def mirror_mode_get(self, ioctx):
"""
Get pool mirror mode.
:param ioctx: determines which RADOS pool is read
:type ioctx: :class:`rados.Ioctx`
:returns: int - pool mirror mode
"""
cdef:
rados_ioctx_t _ioctx = convert_ioctx(ioctx)
rbd_mirror_mode_t mirror_mode
with nogil:
ret = rbd_mirror_mode_get(_ioctx, &mirror_mode)
if ret != 0:
raise make_ex(ret, 'error getting mirror mode')
return mirror_mode
def mirror_mode_set(self, ioctx, mirror_mode):
"""
Set pool mirror mode.
:param ioctx: determines which RADOS pool is written
:type ioctx: :class:`rados.Ioctx`
:param mirror_mode: mirror mode to set
:type mirror_mode: int
"""
cdef:
rados_ioctx_t _ioctx = convert_ioctx(ioctx)
rbd_mirror_mode_t _mirror_mode = mirror_mode
with nogil:
ret = rbd_mirror_mode_set(_ioctx, _mirror_mode)
if ret != 0:
raise make_ex(ret, 'error setting mirror mode')
def mirror_uuid_get(self, ioctx):
"""
Get pool mirror uuid
:param ioctx: determines which RADOS pool is read
:type ioctx: :class:`rados.Ioctx`
:returns: ste - pool mirror uuid
"""
cdef:
rados_ioctx_t _ioctx = convert_ioctx(ioctx)
char *_uuid = NULL
size_t _max_size = 512
try:
while True:
_uuid = <char *>realloc_chk(_uuid, _max_size)
with nogil:
ret = rbd_mirror_uuid_get(_ioctx, _uuid, &_max_size)
if ret >= 0:
break
elif ret != -errno.ERANGE:
raise make_ex(ret, 'error retrieving mirror uuid')
return decode_cstr(_uuid)
finally:
free(_uuid)
def mirror_peer_bootstrap_create(self, ioctx):
"""
Creates a new RBD mirroring bootstrap token for an
external cluster.
:param ioctx: determines which RADOS pool is written
:type ioctx: :class:`rados.Ioctx`
:returns: str - bootstrap token
"""
cdef:
rados_ioctx_t _ioctx = convert_ioctx(ioctx)
char *_token = NULL
size_t _max_size = 512
try:
while True:
_token = <char *>realloc_chk(_token, _max_size)
with nogil:
ret = rbd_mirror_peer_bootstrap_create(_ioctx, _token,
&_max_size)
if ret >= 0:
break
elif ret != -errno.ERANGE:
raise make_ex(ret, 'error creating bootstrap token')
return decode_cstr(_token)
finally:
free(_token)
def mirror_peer_bootstrap_import(self, ioctx, direction, token):
"""
Import a bootstrap token from an external cluster to
auto-configure the mirror peer.
:param ioctx: determines which RADOS pool is written
:type ioctx: :class:`rados.Ioctx`
:param direction: mirror peer direction
:type direction: int
:param token: bootstrap token
:type token: str
"""
token = cstr(token, 'token')
cdef:
rados_ioctx_t _ioctx = convert_ioctx(ioctx)
rbd_mirror_peer_direction_t _direction = direction
char *_token = token
with nogil:
ret = rbd_mirror_peer_bootstrap_import(_ioctx, _direction, _token)
if ret != 0:
raise make_ex(ret, 'error importing bootstrap token')
def mirror_peer_add(self, ioctx, site_name, client_name,
direction=RBD_MIRROR_PEER_DIRECTION_RX_TX):
"""
Add mirror peer.
:param ioctx: determines which RADOS pool is used
:type ioctx: :class:`rados.Ioctx`
:param site_name: mirror peer site name
:type site_name: str
:param client_name: mirror peer client name
:type client_name: str
:param direction: the direction of the mirroring
:type direction: int
:returns: str - peer uuid
"""
site_name = cstr(site_name, 'site_name')
client_name = cstr(client_name, 'client_name')
cdef:
rados_ioctx_t _ioctx = convert_ioctx(ioctx)
char *_uuid = NULL
size_t _uuid_max_length = 512
rbd_mirror_peer_direction_t _direction = direction
char *_site_name = site_name
char *_client_name = client_name
try:
_uuid = <char *>realloc_chk(_uuid, _uuid_max_length)
ret = rbd_mirror_peer_site_add(_ioctx, _uuid, _uuid_max_length,
_direction, _site_name, _client_name)
if ret != 0:
raise make_ex(ret, 'error adding mirror peer')
return decode_cstr(_uuid)
finally:
free(_uuid)
def mirror_peer_remove(self, ioctx, uuid):
"""
Remove mirror peer.
:param ioctx: determines which RADOS pool is used
:type ioctx: :class:`rados.Ioctx`
:param uuid: peer uuid
:type uuid: str
"""
uuid = cstr(uuid, 'uuid')
cdef:
rados_ioctx_t _ioctx = convert_ioctx(ioctx)
char *_uuid = uuid
with nogil:
ret = rbd_mirror_peer_site_remove(_ioctx, _uuid)
if ret != 0:
raise make_ex(ret, 'error removing mirror peer')
def mirror_peer_list(self, ioctx):
"""
Iterate over the peers of a pool.
:param ioctx: determines which RADOS pool is read
:type ioctx: :class:`rados.Ioctx`
:returns: :class:`MirrorPeerIterator`
"""
return MirrorPeerIterator(ioctx)
def mirror_peer_set_client(self, ioctx, uuid, client_name):
"""
Set mirror peer client name
:param ioctx: determines which RADOS pool is written
:type ioctx: :class:`rados.Ioctx`
:param uuid: uuid of the mirror peer
:type uuid: str
:param client_name: client name of the mirror peer to set
:type client_name: str
"""
uuid = cstr(uuid, 'uuid')
client_name = cstr(client_name, 'client_name')
cdef:
rados_ioctx_t _ioctx = convert_ioctx(ioctx)
char *_uuid = uuid
char *_client_name = client_name
with nogil:
ret = rbd_mirror_peer_site_set_client_name(_ioctx, _uuid,
_client_name)
if ret != 0:
raise make_ex(ret, 'error setting mirror peer client name')
def mirror_peer_set_name(self, ioctx, uuid, site_name):
"""
Set mirror peer site name
:param ioctx: determines which RADOS pool is written
:type ioctx: :class:`rados.Ioctx`
:param uuid: uuid of the mirror peer
:type uuid: str
:param site_name: site name of the mirror peer to set
:type site_name: str
"""
uuid = cstr(uuid, 'uuid')
site_name = cstr(site_name, 'site_name')
cdef:
rados_ioctx_t _ioctx = convert_ioctx(ioctx)
char *_uuid = uuid
char *_site_name = site_name
with nogil:
ret = rbd_mirror_peer_site_set_name(_ioctx, _uuid, _site_name)
if ret != 0:
raise make_ex(ret, 'error setting mirror peer site name')
def mirror_peer_set_cluster(self, ioctx, uuid, cluster_name):
self.mirror_peer_set_name(ioctx, uuid, cluster_name)
def mirror_peer_get_attributes(self, ioctx, uuid):
"""
Get optional mirror peer attributes
:param ioctx: determines which RADOS pool is written
:type ioctx: :class:`rados.Ioctx`
:param uuid: uuid of the mirror peer
:type uuid: str
:returns: dict - contains the following keys:
* ``mon_host`` (str) - monitor addresses
* ``key`` (str) - CephX key
"""
uuid = cstr(uuid, 'uuid')
cdef:
rados_ioctx_t _ioctx = convert_ioctx(ioctx)
char *_uuid = uuid
char *_keys = NULL
char *_vals = NULL
size_t _keys_size = 512
size_t _vals_size = 512
size_t _count = 0
try:
while True:
_keys = <char *>realloc_chk(_keys, _keys_size)
_vals = <char *>realloc_chk(_vals, _vals_size)
with nogil:
ret = rbd_mirror_peer_site_get_attributes(
_ioctx, _uuid, _keys, &_keys_size, _vals, &_vals_size,
&_count)
if ret >= 0:
break
elif ret != -errno.ERANGE:
raise make_ex(ret, 'error getting mirror peer attributes')
keys = [decode_cstr(x) for x in _keys[:_keys_size].split(b'\0')[:-1]]
vals = [decode_cstr(x) for x in _vals[:_vals_size].split(b'\0')[:-1]]
return dict(zip(keys, vals))
finally:
free(_keys)
free(_vals)
def mirror_peer_set_attributes(self, ioctx, uuid, attributes):
"""
Set optional mirror peer attributes
:param ioctx: determines which RADOS pool is written
:type ioctx: :class:`rados.Ioctx`
:param uuid: uuid of the mirror peer
:type uuid: str
:param attributes: 'mon_host' and 'key' attributes
:type attributes: dict
"""
uuid = cstr(uuid, 'uuid')
keys_str = b'\0'.join([cstr(x[0], 'key') for x in attributes.items()])
vals_str = b'\0'.join([cstr(x[1], 'val') for x in attributes.items()])
cdef:
rados_ioctx_t _ioctx = convert_ioctx(ioctx)
char *_uuid = uuid
char *_keys = keys_str
char *_vals = vals_str
size_t _count = len(attributes)
with nogil:
ret = rbd_mirror_peer_site_set_attributes(_ioctx, _uuid, _keys,
_vals, _count)
if ret != 0:
raise make_ex(ret, 'error setting mirror peer attributes')
def mirror_image_status_list(self, ioctx):
"""
Iterate over the mirror image statuses of a pool.
:param ioctx: determines which RADOS pool is read
:type ioctx: :class:`rados.Ioctx`
:returns: :class:`MirrorImageStatusIterator`
"""
return MirrorImageStatusIterator(ioctx)
def mirror_image_status_summary(self, ioctx):
"""
Get mirror image status summary of a pool.
:param ioctx: determines which RADOS pool is read
:type ioctx: :class:`rados.Ioctx`
:returns: list - a list of (state, count) tuples
"""
cdef:
rados_ioctx_t _ioctx = convert_ioctx(ioctx)
rbd_mirror_image_status_state_t *states = NULL
int *counts = NULL
size_t maxlen = 32
try:
states = <rbd_mirror_image_status_state_t *>realloc_chk(states,
sizeof(rbd_mirror_image_status_state_t) * maxlen)
counts = <int *>realloc_chk(counts, sizeof(int) * maxlen)
with nogil:
ret = rbd_mirror_image_status_summary(_ioctx, states, counts,
&maxlen)
if ret < 0:
raise make_ex(ret, 'error getting mirror image status summary')
return [(states[i], counts[i]) for i in range(maxlen)]
finally:
free(states)
free(counts)
def mirror_image_instance_id_list(self, ioctx):
"""
Iterate over the mirror image instance ids of a pool.
:param ioctx: determines which RADOS pool is read
:type ioctx: :class:`rados.Ioctx`
:returns: :class:`MirrorImageInstanceIdIterator`
"""
return MirrorImageInstanceIdIterator(ioctx)
def mirror_image_info_list(self, ioctx, mode_filter=None):
"""
Iterate over the mirror image instance ids of a pool.
:param ioctx: determines which RADOS pool is read
:param mode_filter: list images in this image mirror mode
:type ioctx: :class:`rados.Ioctx`
:returns: :class:`MirrorImageInfoIterator`
"""
return MirrorImageInfoIterator(ioctx, mode_filter)
def pool_metadata_get(self, ioctx, key):
"""
Get pool metadata for the given key.
:param ioctx: determines which RADOS pool is read
:type ioctx: :class:`rados.Ioctx`
:param key: metadata key
:type key: str
:returns: str - metadata value
"""
key = cstr(key, 'key')
cdef:
rados_ioctx_t _ioctx = convert_ioctx(ioctx)
char *_key = key
size_t size = 4096
char *value = NULL
int ret
try:
while True:
value = <char *>realloc_chk(value, size)
with nogil:
ret = rbd_pool_metadata_get(_ioctx, _key, value, &size)
if ret != -errno.ERANGE:
break
if ret == -errno.ENOENT:
raise KeyError('no metadata %s' % (key))
if ret != 0:
raise make_ex(ret, 'error getting metadata %s' % (key))
return decode_cstr(value)
finally:
free(value)
def pool_metadata_set(self, ioctx, key, value):
"""
Set pool metadata for the given key.
:param ioctx: determines which RADOS pool is read
:type ioctx: :class:`rados.Ioctx`
:param key: metadata key
:type key: str
:param value: metadata value
:type value: str
"""
key = cstr(key, 'key')
value = cstr(value, 'value')
cdef:
rados_ioctx_t _ioctx = convert_ioctx(ioctx)
char *_key = key
char *_value = value
with nogil:
ret = rbd_pool_metadata_set(_ioctx, _key, _value)
if ret != 0:
raise make_ex(ret, 'error setting metadata %s' % (key))
def pool_metadata_remove(self, ioctx, key):
"""
Remove pool metadata for the given key.
:param ioctx: determines which RADOS pool is read
:type ioctx: :class:`rados.Ioctx`
:param key: metadata key
:type key: str
:returns: str - metadata value
"""
key = cstr(key, 'key')
cdef:
rados_ioctx_t _ioctx = convert_ioctx(ioctx)
char *_key = key
with nogil:
ret = rbd_pool_metadata_remove(_ioctx, _key)
if ret == -errno.ENOENT:
raise KeyError('no metadata %s' % (key))
if ret != 0:
raise make_ex(ret, 'error removing metadata %s' % (key))
def pool_metadata_list(self, ioctx):
"""
List pool metadata.
:returns: :class:`PoolMetadataIterator`
"""
return PoolMetadataIterator(ioctx)
def config_list(self, ioctx):
"""
List pool-level config overrides.
:returns: :class:`ConfigPoolIterator`
"""
return ConfigPoolIterator(ioctx)
def config_get(self, ioctx, key):
"""
Get a pool-level configuration override.
:param ioctx: determines which RADOS pool is read
:type ioctx: :class:`rados.Ioctx`
:param key: key
:type key: str
:returns: str - value
"""
conf_key = 'conf_' + key
conf_key = cstr(conf_key, 'key')
cdef:
rados_ioctx_t _ioctx = convert_ioctx(ioctx)
char *_key = conf_key
size_t size = 4096
char *value = NULL
int ret
try:
while True:
value = <char *>realloc_chk(value, size)
with nogil:
ret = rbd_pool_metadata_get(_ioctx, _key, value, &size)
if ret != -errno.ERANGE:
break
if ret == -errno.ENOENT:
raise KeyError('no config %s for pool %s' % (key, ioctx.get_pool_name()))
if ret != 0:
raise make_ex(ret, 'error getting config %s for pool %s' %
(key, ioctx.get_pool_name()))
return decode_cstr(value)
finally:
free(value)
def config_set(self, ioctx, key, value):
"""
Get a pool-level configuration override.
:param ioctx: determines which RADOS pool is read
:type ioctx: :class:`rados.Ioctx`
:param key: key
:type key: str
:param value: value
:type value: str
"""
conf_key = 'conf_' + key
conf_key = cstr(conf_key, 'key')
value = cstr(value, 'value')
cdef:
rados_ioctx_t _ioctx = convert_ioctx(ioctx)
char *_key = conf_key
char *_value = value
with nogil:
ret = rbd_pool_metadata_set(_ioctx, _key, _value)
if ret != 0:
raise make_ex(ret, 'error setting config %s for pool %s' %
(key, ioctx.get_pool_name()))
def config_remove(self, ioctx, key):
"""
Remove a pool-level configuration override.
:param ioctx: determines which RADOS pool is read
:type ioctx: :class:`rados.Ioctx`
:param key: key
:type key: str
:returns: str - value
"""
conf_key = 'conf_' + key
conf_key = cstr(conf_key, 'key')
cdef:
rados_ioctx_t _ioctx = convert_ioctx(ioctx)
char *_key = conf_key
with nogil:
ret = rbd_pool_metadata_remove(_ioctx, _key)
if ret == -errno.ENOENT:
raise KeyError('no config %s for pool %s' %
(key, ioctx.get_pool_name()))
if ret != 0:
raise make_ex(ret, 'error removing config %s for pool %s' %
(key, ioctx.get_pool_name()))
def group_create(self, ioctx, name):
"""
Create a group.
:param ioctx: determines which RADOS pool is used
:type ioctx: :class:`rados.Ioctx`
:param name: the name of the group
:type name: str
:raises: :class:`ObjectExists`
:raises: :class:`InvalidArgument`
:raises: :class:`FunctionNotSupported`
"""
name = cstr(name, 'name')
cdef:
char *_name = name
rados_ioctx_t _ioctx = convert_ioctx(ioctx)
with nogil:
ret = rbd_group_create(_ioctx, _name)
if ret != 0:
raise make_ex(ret, 'error creating group %s' % name, group_errno_to_exception)
def group_remove(self, ioctx, name):
"""
Delete an RBD group. This may take a long time, since it does
not return until every image in the group has been removed
from the group.
:param ioctx: determines which RADOS pool the group is in
:type ioctx: :class:`rados.Ioctx`
:param name: the name of the group to remove
:type name: str
:raises: :class:`ObjectNotFound`
:raises: :class:`InvalidArgument`
:raises: :class:`FunctionNotSupported`
"""
name = cstr(name, 'name')
cdef:
rados_ioctx_t _ioctx = convert_ioctx(ioctx)
char *_name = name
with nogil:
ret = rbd_group_remove(_ioctx, _name)
if ret != 0:
raise make_ex(ret, 'error removing group', group_errno_to_exception)
def group_list(self, ioctx):
"""
List groups.
:param ioctx: determines which RADOS pool is read
:type ioctx: :class:`rados.Ioctx`
:returns: list -- a list of groups names
:raises: :class:`FunctionNotSupported`
"""
cdef:
rados_ioctx_t _ioctx = convert_ioctx(ioctx)
size_t size = 512
char *c_names = NULL
try:
while True:
c_names = <char *>realloc_chk(c_names, size)
with nogil:
ret = rbd_group_list(_ioctx, c_names, &size)
if ret >= 0:
break
elif ret != -errno.ERANGE:
raise make_ex(ret, 'error listing groups', group_errno_to_exception)
return [decode_cstr(name) for name in c_names[:ret].split(b'\0')
if name]
finally:
free(c_names)
def group_rename(self, ioctx, src, dest):
"""
Rename an RBD group.
:param ioctx: determines which RADOS pool the group is in
:type ioctx: :class:`rados.Ioctx`
:param src: the current name of the group
:type src: str
:param dest: the new name of the group
:type dest: str
:raises: :class:`ObjectExists`
:raises: :class:`ObjectNotFound`
:raises: :class:`InvalidArgument`
:raises: :class:`FunctionNotSupported`
"""
src = cstr(src, 'src')
dest = cstr(dest, 'dest')
cdef:
rados_ioctx_t _ioctx = convert_ioctx(ioctx)
char *_src = src
char *_dest = dest
with nogil:
ret = rbd_group_rename(_ioctx, _src, _dest)
if ret != 0:
raise make_ex(ret, 'error renaming group')
def namespace_create(self, ioctx, name):
"""
Create an RBD namespace within a pool
:param ioctx: determines which RADOS pool
:type ioctx: :class:`rados.Ioctx`
:param name: namespace name
:type name: str
"""
name = cstr(name, 'name')
cdef:
rados_ioctx_t _ioctx = convert_ioctx(ioctx)
const char *_name = name
with nogil:
ret = rbd_namespace_create(_ioctx, _name)
if ret != 0:
raise make_ex(ret, 'error creating namespace')
def namespace_remove(self, ioctx, name):
"""
Remove an RBD namespace from a pool
:param ioctx: determines which RADOS pool
:type ioctx: :class:`rados.Ioctx`
:param name: namespace name
:type name: str
"""
name = cstr(name, 'name')
cdef:
rados_ioctx_t _ioctx = convert_ioctx(ioctx)
const char *_name = name
with nogil:
ret = rbd_namespace_remove(_ioctx, _name)
if ret != 0:
raise make_ex(ret, 'error removing namespace')
def namespace_exists(self, ioctx, name):
"""
Verifies if a namespace exists within a pool
:param ioctx: determines which RADOS pool
:type ioctx: :class:`rados.Ioctx`
:param name: namespace name
:type name: str
:returns: bool - true if namespace exists
"""
name = cstr(name, 'name')
cdef:
rados_ioctx_t _ioctx = convert_ioctx(ioctx)
const char *_name = name
bint _exists = False
with nogil:
ret = rbd_namespace_exists(_ioctx, _name, &_exists)
if ret != 0:
raise make_ex(ret, 'error verifying namespace')
return bool(_exists != 0)
def namespace_list(self, ioctx):
"""
List all namespaces within a pool
:param ioctx: determines which RADOS pool
:type ioctx: :class:`rados.Ioctx`
:returns: list - collection of namespace names
"""
cdef:
rados_ioctx_t _ioctx = convert_ioctx(ioctx)
char *_names = NULL
size_t _size = 512
try:
while True:
_names = <char *>realloc_chk(_names, _size)
with nogil:
ret = rbd_namespace_list(_ioctx, _names, &_size)
if ret >= 0:
break
elif ret != -errno.ERANGE:
raise make_ex(ret, 'error listing namespaces')
return [decode_cstr(name) for name in _names[:_size].split(b'\0')
if name]
finally:
free(_names)
def pool_init(self, ioctx, force):
"""
Initialize an RBD pool
:param ioctx: determines which RADOS pool
:type ioctx: :class:`rados.Ioctx`
:param force: force init
:type force: bool
"""
cdef:
rados_ioctx_t _ioctx = convert_ioctx(ioctx)
bint _force = force
with nogil:
ret = rbd_pool_init(_ioctx, _force)
if ret != 0:
raise make_ex(ret, 'error initializing pool')
def pool_stats_get(self, ioctx):
"""
Return RBD pool stats
:param ioctx: determines which RADOS pool
:type ioctx: :class:`rados.Ioctx`
:returns: dict - contains the following keys:
* ``image_count`` (int) - image count
* ``image_provisioned_bytes`` (int) - image total HEAD provisioned bytes
* ``image_max_provisioned_bytes`` (int) - image total max provisioned bytes
* ``image_snap_count`` (int) - image snap count
* ``trash_count`` (int) - trash image count
* ``trash_provisioned_bytes`` (int) - trash total HEAD provisioned bytes
* ``trash_max_provisioned_bytes`` (int) - trash total max provisioned bytes
* ``trash_snap_count`` (int) - trash snap count
"""
cdef:
rados_ioctx_t _ioctx = convert_ioctx(ioctx)
uint64_t _image_count = 0
uint64_t _image_provisioned_bytes = 0
uint64_t _image_max_provisioned_bytes = 0
uint64_t _image_snap_count = 0
uint64_t _trash_count = 0
uint64_t _trash_provisioned_bytes = 0
uint64_t _trash_max_provisioned_bytes = 0
uint64_t _trash_snap_count = 0
rbd_pool_stats_t _stats
rbd_pool_stats_create(&_stats)
rbd_pool_stats_option_add_uint64(_stats, RBD_POOL_STAT_OPTION_IMAGES,
&_image_count)
rbd_pool_stats_option_add_uint64(_stats, RBD_POOL_STAT_OPTION_IMAGE_PROVISIONED_BYTES,
&_image_provisioned_bytes)
rbd_pool_stats_option_add_uint64(_stats, RBD_POOL_STAT_OPTION_IMAGE_MAX_PROVISIONED_BYTES,
&_image_max_provisioned_bytes)
rbd_pool_stats_option_add_uint64(_stats, RBD_POOL_STAT_OPTION_IMAGE_SNAPSHOTS,
&_image_snap_count)
rbd_pool_stats_option_add_uint64(_stats, RBD_POOL_STAT_OPTION_TRASH_IMAGES,
&_trash_count)
rbd_pool_stats_option_add_uint64(_stats, RBD_POOL_STAT_OPTION_TRASH_PROVISIONED_BYTES,
&_trash_provisioned_bytes)
rbd_pool_stats_option_add_uint64(_stats, RBD_POOL_STAT_OPTION_TRASH_MAX_PROVISIONED_BYTES,
&_trash_max_provisioned_bytes)
rbd_pool_stats_option_add_uint64(_stats, RBD_POOL_STAT_OPTION_TRASH_SNAPSHOTS,
&_trash_snap_count)
try:
with nogil:
ret = rbd_pool_stats_get(_ioctx, _stats)
if ret != 0:
raise make_ex(ret, 'error retrieving pool stats')
else:
return {'image_count': _image_count,
'image_provisioned_bytes': _image_provisioned_bytes,
'image_max_provisioned_bytes': _image_max_provisioned_bytes,
'image_snap_count': _image_snap_count,
'trash_count': _trash_count,
'trash_provisioned_bytes': _trash_provisioned_bytes,
'trash_max_provisioned_bytes': _trash_max_provisioned_bytes,
'trash_snap_count': _trash_snap_count}
finally:
rbd_pool_stats_destroy(_stats)
def features_to_string(self, features):
"""
Convert features bitmask to str.
:param features: feature bitmask
:type features: int
:returns: str - the features str of the image
:raises: :class:`InvalidArgument`
"""
cdef:
int ret = -errno.ERANGE
uint64_t _features = features
size_t size = 1024
char *str_features = NULL
try:
while ret == -errno.ERANGE:
str_features = <char *>realloc_chk(str_features, size)
with nogil:
ret = rbd_features_to_string(_features, str_features, &size)
if ret != 0:
raise make_ex(ret, 'error converting features bitmask to str')
return decode_cstr(str_features)
finally:
free(str_features)
def features_from_string(self, str_features):
"""
Get features bitmask from str, if str_features is empty, it will return
RBD_FEATURES_DEFAULT.
:param str_features: feature str
:type str_features: str
:returns: int - the features bitmask of the image
:raises: :class:`InvalidArgument`
"""
str_features = cstr(str_features, 'str_features')
cdef:
const char *_str_features = str_features
uint64_t features
with nogil:
ret = rbd_features_from_string(_str_features, &features)
if ret != 0:
raise make_ex(ret, 'error getting features bitmask from str')
return features
def aio_open_image(self, oncomplete, ioctx, name=None, snapshot=None,
read_only=False, image_id=None):
"""
Asynchronously open the image at the given snapshot.
Specify either name or id, otherwise :class:`InvalidArgument` is raised.
oncomplete will be called with the created Image object as
well as the completion:
oncomplete(completion, image)
If a snapshot is specified, the image will be read-only, unless
:func:`Image.set_snap` is called later.
If read-only mode is used, metadata for the :class:`Image`
object (such as which snapshots exist) may become obsolete. See
the C api for more details.
To clean up from opening the image, :func:`Image.close` or
:func:`Image.aio_close` should be called.
:param oncomplete: what to do when open is complete
:type oncomplete: completion
:param ioctx: determines which RADOS pool the image is in
:type ioctx: :class:`rados.Ioctx`
:param name: the name of the image
:type name: str
:param snapshot: which snapshot to read from
:type snaphshot: str
:param read_only: whether to open the image in read-only mode
:type read_only: bool
:param image_id: the id of the image
:type image_id: str
:returns: :class:`Completion` - the completion object
"""
image = Image(ioctx, name, snapshot, read_only, image_id, oncomplete)
comp, image._open_completion = image._open_completion, None
return comp
cdef class MirrorPeerIterator(object):
"""
Iterator over mirror peer info for a pool.
Yields a dictionary containing information about a peer.
Keys are:
* ``uuid`` (str) - uuid of the peer
* ``direction`` (int) - direction enum
* ``site_name`` (str) - cluster name of the peer
* ``mirror_uuid`` (str) - mirror uuid of the peer
* ``client_name`` (str) - client name of the peer
"""
cdef:
rbd_mirror_peer_site_t *peers
int num_peers
def __init__(self, ioctx):
cdef:
rados_ioctx_t _ioctx = convert_ioctx(ioctx)
self.peers = NULL
self.num_peers = 10
while True:
self.peers = <rbd_mirror_peer_site_t *>realloc_chk(
self.peers, self.num_peers * sizeof(rbd_mirror_peer_site_t))
with nogil:
ret = rbd_mirror_peer_site_list(_ioctx, self.peers,
&self.num_peers)
if ret < 0:
if ret == -errno.ERANGE:
continue
self.num_peers = 0
raise make_ex(ret, 'error listing peers')
break
def __iter__(self):
for i in range(self.num_peers):
yield {
'uuid' : decode_cstr(self.peers[i].uuid),
'direction' : int(self.peers[i].direction),
'site_name' : decode_cstr(self.peers[i].site_name),
'cluster_name' : decode_cstr(self.peers[i].site_name),
'mirror_uuid' : decode_cstr(self.peers[i].mirror_uuid),
'client_name' : decode_cstr(self.peers[i].client_name),
}
def __dealloc__(self):
if self.peers:
rbd_mirror_peer_site_list_cleanup(self.peers, self.num_peers)
free(self.peers)
cdef class MirrorImageStatusIterator(object):
"""
Iterator over mirror image status for a pool.
Yields a dictionary containing mirror status of an image.
Keys are:
* ``name`` (str) - mirror image name
* ``id`` (str) - mirror image id
* ``info`` (dict) - mirror image info
* ``state`` (int) - status mirror state
* ``description`` (str) - status description
* ``last_update`` (datetime) - last status update time
* ``up`` (bool) - is mirroring agent up
* ``remote_statuses`` (array) -
* ``mirror uuid`` (str) - remote mirror uuid
* ``state`` (int) - status mirror state
* ``description`` (str) - status description
* ``last_update`` (datetime) - last status update time
* ``up`` (bool) - is mirroring agent up
"""
cdef:
rados_ioctx_t ioctx
size_t max_read
char *last_read
char **image_ids
rbd_mirror_image_site_status_t *s_status
rbd_mirror_image_global_status_t *images
size_t size
def __init__(self, ioctx):
self.ioctx = convert_ioctx(ioctx)
self.max_read = 1024
self.last_read = strdup("")
self.image_ids = <char **>realloc_chk(NULL,
sizeof(char *) * self.max_read)
self.images = <rbd_mirror_image_global_status_t *>realloc_chk(NULL,
sizeof(rbd_mirror_image_global_status_t) * self.max_read)
self.size = 0
self.get_next_chunk()
def __iter__(self):
while self.size > 0:
for i in range(self.size):
local_status = None
site_statuses = []
for x in range(self.images[i].site_statuses_count):
s_status = &self.images[i].site_statuses[x]
site_status = {
'state' : s_status.state,
'description' : decode_cstr(s_status.description),
'last_update' : datetime.utcfromtimestamp(s_status.last_update),
'up' : s_status.up,
}
mirror_uuid = decode_cstr(s_status.mirror_uuid)
if mirror_uuid == '':
local_status = site_status
else:
site_status['mirror_uuid'] = mirror_uuid
site_statuses.append(site_status)
status = {
'name' : decode_cstr(self.images[i].name),
'id' : decode_cstr(self.image_ids[i]),
'info' : {
'global_id' : decode_cstr(self.images[i].info.global_id),
'state' : self.images[i].info.state,
# primary isn't added here because it is unknown (always
# false, see XXX in Mirror::image_global_status_list())
},
'remote_statuses': site_statuses,
}
if local_status:
status.update(local_status)
yield status
if self.size < self.max_read:
break
self.get_next_chunk()
def __dealloc__(self):
rbd_mirror_image_global_status_list_cleanup(self.image_ids, self.images,
self.size)
if self.last_read:
free(self.last_read)
if self.image_ids:
free(self.image_ids)
if self.images:
free(self.images)
def get_next_chunk(self):
if self.size > 0:
rbd_mirror_image_global_status_list_cleanup(self.image_ids,
self.images,
self.size)
self.size = 0
with nogil:
ret = rbd_mirror_image_global_status_list(self.ioctx,
self.last_read,
self.max_read,
self.image_ids,
self.images, &self.size)
if ret < 0:
raise make_ex(ret, 'error listing mirror images status')
if self.size > 0:
last_read = cstr(self.image_ids[self.size - 1], 'last_read')
free(self.last_read)
self.last_read = strdup(last_read)
else:
free(self.last_read)
self.last_read = strdup("")
cdef class MirrorImageInstanceIdIterator(object):
"""
Iterator over mirror image instance id for a pool.
Yields ``(image_id, instance_id)`` tuple.
"""
cdef:
rados_ioctx_t ioctx
size_t max_read
char *last_read
char **image_ids
char **instance_ids
size_t size
def __init__(self, ioctx):
self.ioctx = convert_ioctx(ioctx)
self.max_read = 1024
self.last_read = strdup("")
self.image_ids = <char **>realloc_chk(NULL,
sizeof(char *) * self.max_read)
self.instance_ids = <char **>realloc_chk(NULL,
sizeof(char *) * self.max_read)
self.size = 0
self.get_next_chunk()
def __iter__(self):
while self.size > 0:
for i in range(self.size):
yield (decode_cstr(self.image_ids[i]),
decode_cstr(self.instance_ids[i]))
if self.size < self.max_read:
break
self.get_next_chunk()
def __dealloc__(self):
rbd_mirror_image_instance_id_list_cleanup(self.image_ids,
self.instance_ids, self.size)
if self.last_read:
free(self.last_read)
if self.image_ids:
free(self.image_ids)
if self.instance_ids:
free(self.instance_ids)
def get_next_chunk(self):
if self.size > 0:
rbd_mirror_image_instance_id_list_cleanup(self.image_ids,
self.instance_ids,
self.size)
self.size = 0
with nogil:
ret = rbd_mirror_image_instance_id_list(self.ioctx, self.last_read,
self.max_read,
self.image_ids,
self.instance_ids,
&self.size)
if ret < 0:
raise make_ex(ret, 'error listing mirror images instance ids')
if self.size > 0:
last_read = cstr(self.image_ids[self.size - 1], 'last_read')
free(self.last_read)
self.last_read = strdup(last_read)
else:
free(self.last_read)
self.last_read = strdup("")
cdef class MirrorImageInfoIterator(object):
"""
Iterator over mirror image info for a pool.
Yields ``(image_id, info)`` tuple.
"""
cdef:
rados_ioctx_t ioctx
rbd_mirror_image_mode_t mode_filter
rbd_mirror_image_mode_t *mode_filter_ptr
size_t max_read
char *last_read
char **image_ids
rbd_mirror_image_info_t *info_entries
rbd_mirror_image_mode_t *mode_entries
size_t size
def __init__(self, ioctx, mode_filter):
self.ioctx = convert_ioctx(ioctx)
if mode_filter is not None:
self.mode_filter = mode_filter
self.mode_filter_ptr = &self.mode_filter
else:
self.mode_filter_ptr = NULL
self.max_read = 1024
self.last_read = strdup("")
self.image_ids = <char **>realloc_chk(NULL,
sizeof(char *) * self.max_read)
self.info_entries = <rbd_mirror_image_info_t *>realloc_chk(NULL,
sizeof(rbd_mirror_image_info_t) * self.max_read)
self.mode_entries = <rbd_mirror_image_mode_t *>realloc_chk(NULL,
sizeof(rbd_mirror_image_mode_t) * self.max_read)
self.size = 0
self.get_next_chunk()
def __iter__(self):
while self.size > 0:
for i in range(self.size):
yield (decode_cstr(self.image_ids[i]),
{
'mode' : int(self.mode_entries[i]),
'global_id' : decode_cstr(self.info_entries[i].global_id),
'state' : int(self.info_entries[i].state),
'primary' : self.info_entries[i].primary,
})
if self.size < self.max_read:
break
self.get_next_chunk()
def __dealloc__(self):
rbd_mirror_image_info_list_cleanup(self.image_ids, self.info_entries,
self.size)
if self.last_read:
free(self.last_read)
if self.image_ids:
free(self.image_ids)
if self.info_entries:
free(self.info_entries)
if self.mode_entries:
free(self.mode_entries)
def get_next_chunk(self):
if self.size > 0:
rbd_mirror_image_info_list_cleanup(self.image_ids,
self.info_entries, self.size)
self.size = 0
with nogil:
ret = rbd_mirror_image_info_list(self.ioctx, self.mode_filter_ptr,
self.last_read, self.max_read,
self.image_ids, self.mode_entries,
self.info_entries, &self.size)
if ret < 0:
raise make_ex(ret, 'error listing mirror image info')
if self.size > 0:
last_read = cstr(self.image_ids[self.size - 1], 'last_read')
free(self.last_read)
self.last_read = strdup(last_read)
else:
free(self.last_read)
self.last_read = strdup("")
cdef class PoolMetadataIterator(object):
"""
Iterator over pool metadata list.
Yields ``(key, value)`` tuple.
* ``key`` (str) - metadata key
* ``value`` (str) - metadata value
"""
cdef:
rados_ioctx_t ioctx
char *last_read
uint64_t max_read
object next_chunk
def __init__(self, ioctx):
self.ioctx = convert_ioctx(ioctx)
self.last_read = strdup("")
self.max_read = 32
self.get_next_chunk()
def __iter__(self):
while len(self.next_chunk) > 0:
for pair in self.next_chunk:
yield pair
if len(self.next_chunk) < self.max_read:
break
self.get_next_chunk()
def __dealloc__(self):
if self.last_read:
free(self.last_read)
def get_next_chunk(self):
cdef:
char *c_keys = NULL
size_t keys_size = 4096
char *c_vals = NULL
size_t vals_size = 4096
try:
while True:
c_keys = <char *>realloc_chk(c_keys, keys_size)
c_vals = <char *>realloc_chk(c_vals, vals_size)
with nogil:
ret = rbd_pool_metadata_list(self.ioctx, self.last_read,
self.max_read, c_keys,
&keys_size, c_vals, &vals_size)
if ret >= 0:
break
elif ret != -errno.ERANGE:
raise make_ex(ret, 'error listing metadata')
keys = [decode_cstr(key) for key in
c_keys[:keys_size].split(b'\0') if key]
vals = [decode_cstr(val) for val in
c_vals[:vals_size].split(b'\0') if val]
if len(keys) > 0:
last_read = cstr(keys[-1], 'last_read')
free(self.last_read)
self.last_read = strdup(last_read)
self.next_chunk = list(zip(keys, vals))
finally:
free(c_keys)
free(c_vals)
cdef class ConfigPoolIterator(object):
"""
Iterator over pool-level overrides for a pool.
Yields a dictionary containing information about an override.
Keys are:
* ``name`` (str) - override name
* ``value`` (str) - override value
* ``source`` (str) - override source
"""
cdef:
rbd_config_option_t *options
int num_options
def __init__(self, ioctx):
cdef:
rados_ioctx_t _ioctx = convert_ioctx(ioctx)
self.options = NULL
self.num_options = 32
while True:
self.options = <rbd_config_option_t *>realloc_chk(
self.options, self.num_options * sizeof(rbd_config_option_t))
with nogil:
ret = rbd_config_pool_list(_ioctx, self.options, &self.num_options)
if ret < 0:
if ret == -errno.ERANGE:
continue
self.num_options = 0
raise make_ex(ret, 'error listing config options')
break
def __iter__(self):
for i in range(self.num_options):
yield {
'name' : decode_cstr(self.options[i].name),
'value' : decode_cstr(self.options[i].value),
'source' : self.options[i].source,
}
def __dealloc__(self):
if self.options:
rbd_config_pool_list_cleanup(self.options, self.num_options)
free(self.options)
cdef int diff_iterate_cb(uint64_t offset, size_t length, int write, void *cb) \
except? -9000 with gil:
# Make sure that if we wound up with an exception from a previous callback,
# we stop calling back (just in case librbd ever fails to bail out on the
# first negative return, as older versions did)
if exc.PyErr_Occurred():
return -9000
ret = (<object>cb)(offset, length, bool(write))
if ret is None:
return 0
return ret
cdef class Group(object):
"""
This class represents an RBD group. It is used to interact with
snapshots and images members.
"""
cdef object name
cdef char *_name
cdef object ioctx
cdef rados_ioctx_t _ioctx
def __init__(self, ioctx, name):
name = cstr(name, 'name')
self.name = name
self._ioctx = convert_ioctx(ioctx)
self._name = name
def __enter__(self):
return self
def __exit__(self, type_, value, traceback):
return False
def add_image(self, image_ioctx, image_name):
"""
Add an image to a group.
:param image_ioctx: determines which RADOS pool the image belongs to.
:type ioctx: :class:`rados.Ioctx`
:param name: the name of the image to add
:type name: str
:raises: :class:`ObjectNotFound`
:raises: :class:`ObjectExists`
:raises: :class:`InvalidArgument`
:raises: :class:`FunctionNotSupported`
"""
image_name = cstr(image_name, 'image_name')
cdef:
rados_ioctx_t _image_ioctx = convert_ioctx(image_ioctx)
char *_image_name = image_name
with nogil:
ret = rbd_group_image_add(self._ioctx, self._name, _image_ioctx, _image_name)
if ret != 0:
raise make_ex(ret, 'error adding image to group', group_errno_to_exception)
def remove_image(self, image_ioctx, image_name):
"""
Remove an image from a group.
:param image_ioctx: determines which RADOS pool the image belongs to.
:type ioctx: :class:`rados.Ioctx`
:param name: the name of the image to remove
:type name: str
:raises: :class:`ObjectNotFound`
:raises: :class:`InvalidArgument`
:raises: :class:`FunctionNotSupported`
"""
image_name = cstr(image_name, 'image_name')
cdef:
rados_ioctx_t _image_ioctx = convert_ioctx(image_ioctx)
char *_image_name = image_name
with nogil:
ret = rbd_group_image_remove(self._ioctx, self._name, _image_ioctx, _image_name)
if ret != 0:
raise make_ex(ret, 'error removing image from group', group_errno_to_exception)
def list_images(self):
"""
Iterate over the images of a group.
:returns: :class:`GroupImageIterator`
"""
return GroupImageIterator(self)
def create_snap(self, snap_name, flags=0):
"""
Create a snapshot for the group.
:param snap_name: the name of the snapshot to create
:param flags: create snapshot flags
:type name: str
:raises: :class:`ObjectNotFound`
:raises: :class:`ObjectExists`
:raises: :class:`InvalidArgument`
:raises: :class:`FunctionNotSupported`
"""
snap_name = cstr(snap_name, 'snap_name')
cdef:
char *_snap_name = snap_name
uint32_t _flags = flags
with nogil:
ret = rbd_group_snap_create2(self._ioctx, self._name, _snap_name,
_flags)
if ret != 0:
raise make_ex(ret, 'error creating group snapshot', group_errno_to_exception)
def remove_snap(self, snap_name):
"""
Remove a snapshot from the group.
:param snap_name: the name of the snapshot to remove
:type name: str
:raises: :class:`ObjectNotFound`
:raises: :class:`InvalidArgument`
:raises: :class:`FunctionNotSupported`
"""
snap_name = cstr(snap_name, 'snap_name')
cdef:
char *_snap_name = snap_name
with nogil:
ret = rbd_group_snap_remove(self._ioctx, self._name, _snap_name)
if ret != 0:
raise make_ex(ret, 'error removing group snapshot', group_errno_to_exception)
def rename_snap(self, old_snap_name, new_snap_name):
"""
Rename group's snapshot.
:raises: :class:`ObjectNotFound`
:raises: :class:`ObjectExists`
:raises: :class:`InvalidArgument`
:raises: :class:`FunctionNotSupported`
"""
old_snap_name = cstr(old_snap_name, 'old_snap_name')
new_snap_name = cstr(new_snap_name, 'new_snap_name')
cdef:
char *_old_snap_name = old_snap_name
char *_new_snap_name = new_snap_name
with nogil:
ret = rbd_group_snap_rename(self._ioctx, self._name, _old_snap_name,
_new_snap_name)
if ret != 0:
raise make_ex(ret, 'error renaming group snapshot',
group_errno_to_exception)
def list_snaps(self):
"""
Iterate over the images of a group.
:returns: :class:`GroupSnapIterator`
"""
return GroupSnapIterator(self)
def rollback_to_snap(self, name):
"""
Rollback group to snapshot.
:param name: the group snapshot to rollback to
:type name: str
:raises: :class:`ObjectNotFound`
:raises: :class:`IOError`
"""
name = cstr(name, 'name')
cdef char *_name = name
with nogil:
ret = rbd_group_snap_rollback(self._ioctx, self._name, _name)
if ret != 0:
raise make_ex(ret, 'error rolling back group to snapshot', group_errno_to_exception)
def requires_not_closed(f):
def wrapper(self, *args, **kwargs):
self.require_not_closed()
return f(self, *args, **kwargs)
return wrapper
cdef class Image(object):
"""
This class represents an RBD image. It is used to perform I/O on
the image and interact with snapshots.
**Note**: Any method of this class may raise :class:`ImageNotFound`
if the image has been deleted.
"""
cdef rbd_image_t image
cdef bint closed
cdef object name
cdef object ioctx
cdef rados_ioctx_t _ioctx
cdef Completion _open_completion
def __init__(self, ioctx, name=None, snapshot=None,
read_only=False, image_id=None, _oncomplete=None):
"""
Open the image at the given snapshot.
Specify either name or id, otherwise :class:`InvalidArgument` is raised.
If a snapshot is specified, the image will be read-only, unless
:func:`Image.set_snap` is called later.
If read-only mode is used, metadata for the :class:`Image`
object (such as which snapshots exist) may become obsolete. See
the C api for more details.
To clean up from opening the image, :func:`Image.close` should
be called. For ease of use, this is done automatically when
an :class:`Image` is used as a context manager (see :pep:`343`).
:param ioctx: determines which RADOS pool the image is in
:type ioctx: :class:`rados.Ioctx`
:param name: the name of the image
:type name: str
:param snapshot: which snapshot to read from
:type snaphshot: str
:param read_only: whether to open the image in read-only mode
:type read_only: bool
:param image_id: the id of the image
:type image_id: str
"""
name = cstr(name, 'name', opt=True)
image_id = cstr(image_id, 'image_id', opt=True)
snapshot = cstr(snapshot, 'snapshot', opt=True)
self.closed = True
if name is not None and image_id is not None:
raise InvalidArgument("only need to specify image name or image id")
elif name is None and image_id is None:
raise InvalidArgument("image name or image id was not specified")
elif name is not None:
self.name = name
else:
self.name = image_id
# Keep around a reference to the ioctx, so it won't get deleted
self.ioctx = ioctx
cdef:
rados_ioctx_t _ioctx = convert_ioctx(ioctx)
char *_name = opt_str(name)
char *_image_id = opt_str(image_id)
char *_snapshot = opt_str(snapshot)
cdef Completion completion
if _oncomplete:
def oncomplete(completion_v):
cdef Completion _completion_v = completion_v
return_value = _completion_v.get_return_value()
if return_value == 0:
self.closed = False
if name is None:
self.name = self.get_name()
return _oncomplete(_completion_v, self)
completion = self.__get_completion(oncomplete)
try:
completion.__persist()
if read_only:
with nogil:
if name is not None:
ret = rbd_aio_open_read_only(
_ioctx, _name, &self.image, _snapshot,
completion.rbd_comp)
else:
ret = rbd_aio_open_by_id_read_only(
_ioctx, _image_id, &self.image, _snapshot,
completion.rbd_comp)
else:
with nogil:
if name is not None:
ret = rbd_aio_open(
_ioctx, _name, &self.image, _snapshot,
completion.rbd_comp)
else:
ret = rbd_aio_open_by_id(
_ioctx, _image_id, &self.image, _snapshot,
completion.rbd_comp)
if ret != 0:
raise make_ex(ret, 'error opening image %s at snapshot %s' %
(self.name, snapshot))
except:
completion.__unpersist()
raise
self._open_completion = completion
return
if read_only:
with nogil:
if name is not None:
ret = rbd_open_read_only(_ioctx, _name, &self.image, _snapshot)
else:
ret = rbd_open_by_id_read_only(_ioctx, _image_id, &self.image, _snapshot)
else:
with nogil:
if name is not None:
ret = rbd_open(_ioctx, _name, &self.image, _snapshot)
else:
ret = rbd_open_by_id(_ioctx, _image_id, &self.image, _snapshot)
if ret != 0:
raise make_ex(ret, 'error opening image %s at snapshot %s' % (self.name, snapshot))
self.closed = False
if name is None:
self.name = self.get_name()
def __enter__(self):
return self
def __exit__(self, type_, value, traceback):
"""
Closes the image. See :func:`close`
"""
self.close()
return False
def __get_completion(self, oncomplete):
"""
Constructs a completion to use with asynchronous operations
:param oncomplete: callback for the completion
:raises: :class:`Error`
:returns: completion object
"""
completion_obj = Completion(self, oncomplete)
cdef:
rbd_completion_t completion
PyObject* p_completion_obj= <PyObject*>completion_obj
with nogil:
ret = rbd_aio_create_completion(p_completion_obj, __aio_complete_cb,
&completion)
if ret < 0:
raise make_ex(ret, "error getting a completion")
completion_obj.rbd_comp = completion
return completion_obj
def require_not_closed(self):
"""
Checks if the Image is not closed
:raises: :class:`InvalidArgument`
"""
if self.closed:
raise InvalidArgument("image is closed")
def close(self):
"""
Release the resources used by this image object.
After this is called, this object should not be used.
"""
if not self.closed:
self.closed = True
with nogil:
ret = rbd_close(self.image)
if ret < 0:
raise make_ex(ret, 'error while closing image %s' % (
self.name,))
@requires_not_closed
def aio_close(self, oncomplete):
"""
Asynchronously close the image.
After this is called, this object should not be used.
:param oncomplete: what to do when close is complete
:type oncomplete: completion
:returns: :class:`Completion` - the completion object
"""
cdef Completion completion = self.__get_completion(oncomplete)
self.closed = True
try:
completion.__persist()
with nogil:
ret = rbd_aio_close(self.image, completion.rbd_comp)
if ret < 0:
raise make_ex(ret, 'error while closing image %s' %
self.name)
except:
completion.__unpersist()
raise
return completion
def __dealloc__(self):
self.close()
def __repr__(self):
return "rbd.Image(ioctx, %r)" % self.name
@requires_not_closed
def resize(self, size, allow_shrink=True):
"""
Change the size of the image, allow shrink.
:param size: the new size of the image
:type size: int
:param allow_shrink: permit shrinking
:type allow_shrink: bool
"""
old_size = self.size()
if old_size == size:
return
if not allow_shrink and old_size > size:
raise InvalidArgument("error allow_shrink is False but old_size > new_size")
cdef:
uint64_t _size = size
bint _allow_shrink = allow_shrink
librbd_progress_fn_t prog_cb = &no_op_progress_callback
with nogil:
ret = rbd_resize2(self.image, _size, _allow_shrink, prog_cb, NULL)
if ret < 0:
raise make_ex(ret, 'error resizing image %s' % self.name)
@requires_not_closed
def stat(self):
"""
Get information about the image. Currently parent pool and
parent name are always -1 and ''.
:returns: dict - contains the following keys:
* ``size`` (int) - the size of the image in bytes
* ``obj_size`` (int) - the size of each object that comprises the
image
* ``num_objs`` (int) - the number of objects in the image
* ``order`` (int) - log_2(object_size)
* ``block_name_prefix`` (str) - the prefix of the RADOS objects used
to store the image
* ``parent_pool`` (int) - deprecated
* ``parent_name`` (str) - deprecated
See also :meth:`format` and :meth:`features`.
"""
cdef rbd_image_info_t info
with nogil:
ret = rbd_stat(self.image, &info, sizeof(info))
if ret != 0:
raise make_ex(ret, 'error getting info for image %s' % self.name)
return {
'size' : info.size,
'obj_size' : info.obj_size,
'num_objs' : info.num_objs,
'order' : info.order,
'block_name_prefix' : decode_cstr(info.block_name_prefix),
'parent_pool' : info.parent_pool,
'parent_name' : info.parent_name
}
@requires_not_closed
def get_name(self):
"""
Get the RBD image name
:returns: str - image name
"""
cdef:
int ret = -errno.ERANGE
size_t size = 64
char *image_name = NULL
try:
while ret == -errno.ERANGE:
image_name = <char *>realloc_chk(image_name, size)
with nogil:
ret = rbd_get_name(self.image, image_name, &size)
if ret != 0:
raise make_ex(ret, 'error getting name for image %s' % self.name)
return decode_cstr(image_name)
finally:
free(image_name)
@requires_not_closed
def id(self):
"""
Get the RBD v2 internal image id
:returns: str - image id
"""
cdef:
int ret = -errno.ERANGE
size_t size = 32
char *image_id = NULL
try:
while ret == -errno.ERANGE and size <= 4096:
image_id = <char *>realloc_chk(image_id, size)
with nogil:
ret = rbd_get_id(self.image, image_id, size)
if ret == -errno.ERANGE:
size *= 2
if ret != 0:
raise make_ex(ret, 'error getting id for image %s' % self.name)
return decode_cstr(image_id)
finally:
free(image_id)
@requires_not_closed
def block_name_prefix(self):
"""
Get the RBD block name prefix
:returns: str - block name prefix
"""
cdef:
int ret = -errno.ERANGE
size_t size = 32
char *prefix = NULL
try:
while ret == -errno.ERANGE and size <= 4096:
prefix = <char *>realloc_chk(prefix, size)
with nogil:
ret = rbd_get_block_name_prefix(self.image, prefix, size)
if ret == -errno.ERANGE:
size *= 2
if ret != 0:
raise make_ex(ret, 'error getting block name prefix for image %s' % self.name)
return decode_cstr(prefix)
finally:
free(prefix)
@requires_not_closed
def data_pool_id(self):
"""
Get the pool id of the pool where the data of this RBD image is stored.
:returns: int - the pool id
"""
return rbd_get_data_pool_id(self.image)
@requires_not_closed
def get_parent_image_spec(self):
"""
Get spec of the cloned image's parent
:returns: dict - contains the following keys:
* ``pool_name`` (str) - parent pool name
* ``pool_namespace`` (str) - parent pool namespace
* ``image_name`` (str) - parent image name
* ``snap_name`` (str) - parent snapshot name
:raises: :class:`ImageNotFound` if the image doesn't have a parent
"""
cdef:
rbd_linked_image_spec_t parent_spec
rbd_snap_spec_t snap_spec
with nogil:
ret = rbd_get_parent(self.image, &parent_spec, &snap_spec)
if ret != 0:
raise make_ex(ret, 'error getting parent info for image %s' % self.name)
result = {'pool_name': decode_cstr(parent_spec.pool_name),
'pool_namespace': decode_cstr(parent_spec.pool_namespace),
'image_name': decode_cstr(parent_spec.image_name),
'snap_name': decode_cstr(snap_spec.name)}
rbd_linked_image_spec_cleanup(&parent_spec)
rbd_snap_spec_cleanup(&snap_spec)
return result
@requires_not_closed
def parent_info(self):
"""
Deprecated. Use `get_parent_image_spec` instead.
Get information about a cloned image's parent (if any)
:returns: tuple - ``(pool name, image name, snapshot name)`` components
of the parent image
:raises: :class:`ImageNotFound` if the image doesn't have a parent
"""
parent = self.get_parent_image_spec()
return (parent['pool_name'], parent['image_name'], parent['snap_name'])
@requires_not_closed
def parent_id(self):
"""
Get image id of a cloned image's parent (if any)
:returns: str - the parent id
:raises: :class:`ImageNotFound` if the image doesn't have a parent
"""
cdef:
rbd_linked_image_spec_t parent_spec
rbd_snap_spec_t snap_spec
with nogil:
ret = rbd_get_parent(self.image, &parent_spec, &snap_spec)
if ret != 0:
raise make_ex(ret, 'error getting parent info for image %s' % self.name)
result = decode_cstr(parent_spec.image_id)
rbd_linked_image_spec_cleanup(&parent_spec)
rbd_snap_spec_cleanup(&snap_spec)
return result
@requires_not_closed
def migration_source_spec(self):
"""
Get migration source spec (if any)
:returns: dict
:raises: :class:`ImageNotFound` if the image is not migration destination
"""
cdef:
size_t size = 512
char *spec = NULL
try:
while True:
spec = <char *>realloc_chk(spec, size)
with nogil:
ret = rbd_get_migration_source_spec(self.image, spec, &size)
if ret >= 0:
break
elif ret != -errno.ERANGE:
raise make_ex(ret, 'error retrieving migration source')
return json.loads(decode_cstr(spec))
finally:
free(spec)
@requires_not_closed
def old_format(self):
"""
Find out whether the image uses the old RBD format.
:returns: bool - whether the image uses the old RBD format
"""
cdef uint8_t old
with nogil:
ret = rbd_get_old_format(self.image, &old)
if ret != 0:
raise make_ex(ret, 'error getting old_format for image %s' % (self.name))
return old != 0
@requires_not_closed
def size(self):
"""
Get the size of the image. If open to a snapshot, returns the
size of that snapshot.
:returns: int - the size of the image in bytes
"""
cdef uint64_t image_size
with nogil:
ret = rbd_get_size(self.image, &image_size)
if ret != 0:
raise make_ex(ret, 'error getting size for image %s' % (self.name))
return image_size
@requires_not_closed
def features(self):
"""
Get the features bitmask of the image.
:returns: int - the features bitmask of the image
"""
cdef uint64_t features
with nogil:
ret = rbd_get_features(self.image, &features)
if ret != 0:
raise make_ex(ret, 'error getting features for image %s' % (self.name))
return features
@requires_not_closed
def update_features(self, features, enabled):
"""
Update the features bitmask of the image by enabling/disabling
a single feature. The feature must support the ability to be
dynamically enabled/disabled.
:param features: feature bitmask to enable/disable
:type features: int
:param enabled: whether to enable/disable the feature
:type enabled: bool
:raises: :class:`InvalidArgument`
"""
cdef:
uint64_t _features = features
uint8_t _enabled = bool(enabled)
with nogil:
ret = rbd_update_features(self.image, _features, _enabled)
if ret != 0:
raise make_ex(ret, 'error updating features for image %s' %
(self.name))
@requires_not_closed
def op_features(self):
"""
Get the op features bitmask of the image.
:returns: int - the op features bitmask of the image
"""
cdef uint64_t op_features
with nogil:
ret = rbd_get_op_features(self.image, &op_features)
if ret != 0:
raise make_ex(ret, 'error getting op features for image %s' % (self.name))
return op_features
@requires_not_closed
def overlap(self):
"""
Get the number of overlapping bytes between the image and its parent
image. If open to a snapshot, returns the overlap between the snapshot
and the parent image.
:returns: int - the overlap in bytes
:raises: :class:`ImageNotFound` if the image doesn't have a parent
"""
cdef uint64_t overlap
with nogil:
ret = rbd_get_overlap(self.image, &overlap)
if ret != 0:
raise make_ex(ret, 'error getting overlap for image %s' % (self.name))
return overlap
@requires_not_closed
def flags(self):
"""
Get the flags bitmask of the image.
:returns: int - the flags bitmask of the image
"""
cdef uint64_t flags
with nogil:
ret = rbd_get_flags(self.image, &flags)
if ret != 0:
raise make_ex(ret, 'error getting flags for image %s' % (self.name))
return flags
@requires_not_closed
def group(self):
"""
Get information about the image's group.
:returns: dict - contains the following keys:
* ``pool`` (int) - id of the group pool
* ``name`` (str) - name of the group
"""
cdef rbd_group_info_t info
with nogil:
ret = rbd_get_group(self.image, &info, sizeof(info))
if ret != 0:
raise make_ex(ret, 'error getting group for image %s' % self.name)
result = {
'pool' : info.pool,
'name' : decode_cstr(info.name)
}
rbd_group_info_cleanup(&info, sizeof(info))
return result
@requires_not_closed
def is_exclusive_lock_owner(self):
"""
Get the status of the image exclusive lock.
:returns: bool - true if the image is exclusively locked
"""
cdef int owner
with nogil:
ret = rbd_is_exclusive_lock_owner(self.image, &owner)
if ret != 0:
raise make_ex(ret, 'error getting lock status for image %s' % (self.name))
return owner == 1
@requires_not_closed
def copy(self, dest_ioctx, dest_name, features=None, order=None,
stripe_unit=None, stripe_count=None, data_pool=None):
"""
Copy the image to another location.
:param dest_ioctx: determines which pool to copy into
:type dest_ioctx: :class:`rados.Ioctx`
:param dest_name: the name of the copy
:type dest_name: str
:param features: bitmask of features to enable; if set, must include layering
:type features: int
:param order: the image is split into (2**order) byte objects
:type order: int
:param stripe_unit: stripe unit in bytes (default None to let librbd decide)
:type stripe_unit: int
:param stripe_count: objects to stripe over before looping
:type stripe_count: int
:param data_pool: optional separate pool for data blocks
:type data_pool: str
:raises: :class:`TypeError`
:raises: :class:`InvalidArgument`
:raises: :class:`ImageExists`
:raises: :class:`FunctionNotSupported`
:raises: :class:`ArgumentOutOfRange`
"""
dest_name = cstr(dest_name, 'dest_name')
data_pool = cstr(data_pool, 'data_pool', opt=True)
cdef:
rados_ioctx_t _dest_ioctx = convert_ioctx(dest_ioctx)
char *_dest_name = dest_name
rbd_image_options_t opts
rbd_image_options_create(&opts)
try:
if features is not None:
rbd_image_options_set_uint64(opts, RBD_IMAGE_OPTION_FEATURES,
features)
if order is not None:
rbd_image_options_set_uint64(opts, RBD_IMAGE_OPTION_ORDER,
order)
if stripe_unit is not None:
rbd_image_options_set_uint64(opts, RBD_IMAGE_OPTION_STRIPE_UNIT,
stripe_unit)
if stripe_count is not None:
rbd_image_options_set_uint64(opts, RBD_IMAGE_OPTION_STRIPE_COUNT,
stripe_count)
if data_pool is not None:
rbd_image_options_set_string(opts, RBD_IMAGE_OPTION_DATA_POOL,
data_pool)
with nogil:
ret = rbd_copy3(self.image, _dest_ioctx, _dest_name, opts)
finally:
rbd_image_options_destroy(opts)
if ret < 0:
raise make_ex(ret, 'error copying image %s to %s' % (self.name, dest_name))
@requires_not_closed
def deep_copy(self, dest_ioctx, dest_name, features=None, order=None,
stripe_unit=None, stripe_count=None, data_pool=None):
"""
Deep copy the image to another location.
:param dest_ioctx: determines which pool to copy into
:type dest_ioctx: :class:`rados.Ioctx`
:param dest_name: the name of the copy
:type dest_name: str
:param features: bitmask of features to enable; if set, must include layering
:type features: int
:param order: the image is split into (2**order) byte objects
:type order: int
:param stripe_unit: stripe unit in bytes (default None to let librbd decide)
:type stripe_unit: int
:param stripe_count: objects to stripe over before looping
:type stripe_count: int
:param data_pool: optional separate pool for data blocks
:type data_pool: str
:raises: :class:`TypeError`
:raises: :class:`InvalidArgument`
:raises: :class:`ImageExists`
:raises: :class:`FunctionNotSupported`
:raises: :class:`ArgumentOutOfRange`
"""
dest_name = cstr(dest_name, 'dest_name')
data_pool = cstr(data_pool, 'data_pool', opt=True)
cdef:
rados_ioctx_t _dest_ioctx = convert_ioctx(dest_ioctx)
char *_dest_name = dest_name
rbd_image_options_t opts
rbd_image_options_create(&opts)
try:
if features is not None:
rbd_image_options_set_uint64(opts, RBD_IMAGE_OPTION_FEATURES,
features)
if order is not None:
rbd_image_options_set_uint64(opts, RBD_IMAGE_OPTION_ORDER,
order)
if stripe_unit is not None:
rbd_image_options_set_uint64(opts, RBD_IMAGE_OPTION_STRIPE_UNIT,
stripe_unit)
if stripe_count is not None:
rbd_image_options_set_uint64(opts, RBD_IMAGE_OPTION_STRIPE_COUNT,
stripe_count)
if data_pool is not None:
rbd_image_options_set_string(opts, RBD_IMAGE_OPTION_DATA_POOL,
data_pool)
with nogil:
ret = rbd_deep_copy(self.image, _dest_ioctx, _dest_name, opts)
finally:
rbd_image_options_destroy(opts)
if ret < 0:
raise make_ex(ret, 'error copying image %s to %s' % (self.name, dest_name))
@requires_not_closed
def list_snaps(self):
"""
Iterate over the snapshots of an image.
:returns: :class:`SnapIterator`
"""
return SnapIterator(self)
@requires_not_closed
def create_snap(self, name, flags=0):
"""
Create a snapshot of the image.
:param name: the name of the snapshot
:type name: str
:raises: :class:`ImageExists`, :class:`InvalidArgument`
"""
name = cstr(name, 'name')
cdef:
char *_name = name
uint32_t _flags = flags
librbd_progress_fn_t prog_cb = &no_op_progress_callback
with nogil:
ret = rbd_snap_create2(self.image, _name, _flags, prog_cb, NULL)
if ret != 0:
raise make_ex(ret, 'error creating snapshot %s from %s' % (name, self.name))
@requires_not_closed
def rename_snap(self, srcname, dstname):
"""
rename a snapshot of the image.
:param srcname: the src name of the snapshot
:type srcname: str
:param dstname: the dst name of the snapshot
:type dstname: str
:raises: :class:`ImageExists`
"""
srcname = cstr(srcname, 'srcname')
dstname = cstr(dstname, 'dstname')
cdef:
char *_srcname = srcname
char *_dstname = dstname
with nogil:
ret = rbd_snap_rename(self.image, _srcname, _dstname)
if ret != 0:
raise make_ex(ret, 'error renaming snapshot of %s from %s to %s' % (self.name, srcname, dstname))
@requires_not_closed
def remove_snap(self, name):
"""
Delete a snapshot of the image.
:param name: the name of the snapshot
:type name: str
:raises: :class:`IOError`, :class:`ImageBusy`, :class:`ImageNotFound`
"""
name = cstr(name, 'name')
cdef char *_name = name
with nogil:
ret = rbd_snap_remove(self.image, _name)
if ret != 0:
raise make_ex(ret, 'error removing snapshot %s from %s' % (name, self.name))
@requires_not_closed
def remove_snap2(self, name, flags):
"""
Delete a snapshot of the image.
:param name: the name of the snapshot
:param flags: the flags for removal
:type name: str
:raises: :class:`IOError`, :class:`ImageBusy`
"""
self.require_not_closed()
name = cstr(name, 'name')
cdef:
char *_name = name
uint32_t _flags = flags
librbd_progress_fn_t prog_cb = &no_op_progress_callback
with nogil:
ret = rbd_snap_remove2(self.image, _name, _flags, prog_cb, NULL)
if ret != 0:
raise make_ex(ret, 'error removing snapshot %s from %s with flags %lx' % (name, self.name, flags))
@requires_not_closed
def remove_snap_by_id(self, snap_id):
"""
Delete a snapshot of the image by its id.
:param id: the id of the snapshot
:type name: int
:raises: :class:`IOError`, :class:`ImageBusy`
"""
cdef:
uint64_t _snap_id = snap_id
with nogil:
ret = rbd_snap_remove_by_id(self.image, _snap_id)
if ret != 0:
raise make_ex(ret, 'error removing snapshot %s from %s' % (snap_id, self.name))
@requires_not_closed
def rollback_to_snap(self, name):
"""
Revert the image to its contents at a snapshot. This is a
potentially expensive operation, since it rolls back each
object individually.
:param name: the snapshot to rollback to
:type name: str
:raises: :class:`IOError`
"""
name = cstr(name, 'name')
cdef char *_name = name
with nogil:
ret = rbd_snap_rollback(self.image, _name)
if ret != 0:
raise make_ex(ret, 'error rolling back image %s to snapshot %s' % (self.name, name))
@requires_not_closed
def protect_snap(self, name):
"""
Mark a snapshot as protected. This means it can't be deleted
until it is unprotected.
:param name: the snapshot to protect
:type name: str
:raises: :class:`IOError`, :class:`ImageNotFound`
"""
name = cstr(name, 'name')
cdef char *_name = name
with nogil:
ret = rbd_snap_protect(self.image, _name)
if ret != 0:
raise make_ex(ret, 'error protecting snapshot %s@%s' % (self.name, name))
@requires_not_closed
def unprotect_snap(self, name):
"""
Mark a snapshot unprotected. This allows it to be deleted if
it was protected.
:param name: the snapshot to unprotect
:type name: str
:raises: :class:`IOError`, :class:`ImageNotFound`
"""
name = cstr(name, 'name')
cdef char *_name = name
with nogil:
ret = rbd_snap_unprotect(self.image, _name)
if ret != 0:
raise make_ex(ret, 'error unprotecting snapshot %s@%s' % (self.name, name))
@requires_not_closed
def is_protected_snap(self, name):
"""
Find out whether a snapshot is protected from deletion.
:param name: the snapshot to check
:type name: str
:returns: bool - whether the snapshot is protected
:raises: :class:`IOError`, :class:`ImageNotFound`
"""
name = cstr(name, 'name')
cdef:
char *_name = name
int is_protected
with nogil:
ret = rbd_snap_is_protected(self.image, _name, &is_protected)
if ret != 0:
raise make_ex(ret, 'error checking if snapshot %s@%s is protected' % (self.name, name))
return is_protected == 1
@requires_not_closed
def snap_exists(self, name):
"""
Find out whether a snapshot is exists.
:param name: the snapshot to check
:type name: str
:returns: bool - whether the snapshot is exists
"""
name = cstr(name, 'name')
cdef:
char *_name = name
bint _exists = False
with nogil:
ret = rbd_snap_exists(self.image, _name, &_exists)
if ret != 0:
raise make_ex(ret, 'error getting snapshot exists for %s' % self.name)
return bool(_exists != 0)
@requires_not_closed
def get_snap_limit(self):
"""
Get the snapshot limit for an image.
:returns: int - the snapshot limit for an image
"""
cdef:
uint64_t limit
with nogil:
ret = rbd_snap_get_limit(self.image, &limit)
if ret != 0:
raise make_ex(ret, 'error getting snapshot limit for %s' % self.name)
return limit
@requires_not_closed
def set_snap_limit(self, limit):
"""
Set the snapshot limit for an image.
:param limit: the new limit to set
"""
cdef:
uint64_t _limit = limit
with nogil:
ret = rbd_snap_set_limit(self.image, _limit)
if ret != 0:
raise make_ex(ret, 'error setting snapshot limit for %s' % self.name)
return ret
@requires_not_closed
def get_snap_timestamp(self, snap_id):
"""
Get the snapshot timestamp for an image.
:param snap_id: the snapshot id of a snap shot
:returns: datetime - the snapshot timestamp for an image
"""
cdef:
timespec timestamp
uint64_t _snap_id = snap_id
with nogil:
ret = rbd_snap_get_timestamp(self.image, _snap_id, ×tamp)
if ret != 0:
raise make_ex(ret, 'error getting snapshot timestamp for image: %s, snap_id: %d' % (self.name, snap_id))
return datetime.utcfromtimestamp(timestamp.tv_sec)
@requires_not_closed
def remove_snap_limit(self):
"""
Remove the snapshot limit for an image, essentially setting
the limit to the maximum size allowed by the implementation.
"""
with nogil:
ret = rbd_snap_set_limit(self.image, UINT64_MAX)
if ret != 0:
raise make_ex(ret, 'error removing snapshot limit for %s' % self.name)
return ret
@requires_not_closed
def set_snap(self, name):
"""
Set the snapshot to read from. Writes will raise ReadOnlyImage
while a snapshot is set. Pass None to unset the snapshot
(reads come from the current image) , and allow writing again.
:param name: the snapshot to read from, or None to unset the snapshot
:type name: str or None
"""
name = cstr(name, 'name', opt=True)
cdef char *_name = opt_str(name)
with nogil:
ret = rbd_snap_set(self.image, _name)
if ret != 0:
raise make_ex(ret, 'error setting image %s to snapshot %s' % (self.name, name))
@requires_not_closed
def set_snap_by_id(self, snap_id):
"""
Set the snapshot to read from. Writes will raise ReadOnlyImage
while a snapshot is set. Pass None to unset the snapshot
(reads come from the current image) , and allow writing again.
:param snap_id: the snapshot to read from, or None to unset the snapshot
:type snap_id: int
"""
if not snap_id:
snap_id = _LIBRADOS_SNAP_HEAD
cdef int64_t _snap_id = snap_id
with nogil:
ret = rbd_snap_set_by_id(self.image, _snap_id)
if ret != 0:
raise make_ex(ret, 'error setting image %s to snapshot %d' % (self.name, snap_id))
@requires_not_closed
def snap_get_name(self, snap_id):
"""
Get snapshot name by id.
:param snap_id: the snapshot id
:type snap_id: int
:returns: str - snapshot name
:raises: :class:`ImageNotFound`
"""
cdef:
int ret = -errno.ERANGE
int64_t _snap_id = snap_id
size_t size = 512
char *image_name = NULL
try:
while ret == -errno.ERANGE:
image_name = <char *>realloc_chk(image_name, size)
with nogil:
ret = rbd_snap_get_name(self.image, _snap_id, image_name, &size)
if ret != 0:
raise make_ex(ret, 'error snap_get_name.')
return decode_cstr(image_name)
finally:
free(image_name)
@requires_not_closed
def snap_get_id(self, snap_name):
"""
Get snapshot id by name.
:param snap_name: the snapshot name
:type snap_name: str
:returns: int - snapshot id
:raises: :class:`ImageNotFound`
"""
snap_name = cstr(snap_name, 'snap_name')
cdef:
const char *_snap_name = snap_name
uint64_t snap_id
with nogil:
ret = rbd_snap_get_id(self.image, _snap_name, &snap_id)
if ret != 0:
raise make_ex(ret, 'error snap_get_id.')
return snap_id
@requires_not_closed
def read(self, offset, length, fadvise_flags=0):
"""
Read data from the image. Raises :class:`InvalidArgument` if
part of the range specified is outside the image.
:param offset: the offset to start reading at
:type offset: int
:param length: how many bytes to read
:type length: int
:param fadvise_flags: fadvise flags for this read
:type fadvise_flags: int
:returns: str - the data read
:raises: :class:`InvalidArgument`, :class:`IOError`
"""
# This usage of the Python API allows us to construct a string
# that librbd directly reads into, avoiding an extra copy. Although
# strings are normally immutable, this usage is explicitly supported
# for freshly created string objects.
cdef:
char *ret_buf
uint64_t _offset = offset
size_t _length = length
int _fadvise_flags = fadvise_flags
PyObject* ret_s = NULL
ret_s = PyBytes_FromStringAndSize(NULL, length)
try:
ret_buf = PyBytes_AsString(ret_s)
with nogil:
ret = rbd_read2(self.image, _offset, _length, ret_buf,
_fadvise_flags)
if ret < 0:
raise make_ex(ret, 'error reading %s %ld~%ld' % (self.name, offset, length))
if ret != <ssize_t>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)
@requires_not_closed
def diff_iterate(self, offset, length, from_snapshot, iterate_cb,
include_parent = True, whole_object = False):
"""
Iterate over the changed extents of an image.
This will call iterate_cb with three arguments:
(offset, length, exists)
where the changed extent starts at offset bytes, continues for
length bytes, and is full of data (if exists is True) or zeroes
(if exists is False).
If from_snapshot is None, it is interpreted as the beginning
of time and this generates all allocated extents.
The end version is whatever is currently selected (via set_snap)
for the image.
iterate_cb may raise an exception, which will abort the diff and will be
propagated to the caller.
Raises :class:`InvalidArgument` if from_snapshot is after
the currently set snapshot.
Raises :class:`ImageNotFound` if from_snapshot is not the name
of a snapshot of the image.
:param offset: start offset in bytes
:type offset: int
:param length: size of region to report on, in bytes
:type length: int
:param from_snapshot: starting snapshot name, or None
:type from_snapshot: str or None
:param iterate_cb: function to call for each extent
:type iterate_cb: function acception arguments for offset,
length, and exists
:param include_parent: True if full history diff should include parent
:type include_parent: bool
:param whole_object: True if diff extents should cover whole object
:type whole_object: bool
:raises: :class:`InvalidArgument`, :class:`IOError`,
:class:`ImageNotFound`
"""
from_snapshot = cstr(from_snapshot, 'from_snapshot', opt=True)
cdef:
char *_from_snapshot = opt_str(from_snapshot)
uint64_t _offset = offset, _length = length
uint8_t _include_parent = include_parent
uint8_t _whole_object = whole_object
with nogil:
ret = rbd_diff_iterate2(self.image, _from_snapshot, _offset,
_length, _include_parent, _whole_object,
&diff_iterate_cb, <void *>iterate_cb)
if ret < 0:
msg = 'error generating diff from snapshot %s' % from_snapshot
raise make_ex(ret, msg)
@requires_not_closed
def write(self, data, offset, fadvise_flags=0):
"""
Write data to the image. Raises :class:`InvalidArgument` if
part of the write would fall outside the image.
:param data: the data to be written
:type data: bytes
:param offset: where to start writing data
:type offset: int
:param fadvise_flags: fadvise flags for this write
:type fadvise_flags: int
:returns: int - the number of bytes written
:raises: :class:`IncompleteWriteError`, :class:`LogicError`,
:class:`InvalidArgument`, :class:`IOError`
"""
if not isinstance(data, bytes):
raise TypeError('data must be a byte string')
cdef:
uint64_t _offset = offset, length = len(data)
char *_data = data
int _fadvise_flags = fadvise_flags
with nogil:
ret = rbd_write2(self.image, _offset, length, _data, _fadvise_flags)
if ret == <ssize_t>length:
return ret
elif ret < 0:
raise make_ex(ret, "error writing to %s" % self.name)
elif ret < <ssize_t>length:
raise IncompleteWriteError("Wrote only %ld out of %ld bytes" % (ret, length))
else:
raise LogicError("logic error: rbd_write(%s) \
returned %d, but %d was the maximum number of bytes it could have \
written." % (self.name, ret, length))
@requires_not_closed
def discard(self, offset, length):
"""
Trim the range from the image. It will be logically filled
with zeroes.
"""
cdef uint64_t _offset = offset, _length = length
with nogil:
ret = rbd_discard(self.image, _offset, _length)
if ret < 0:
msg = 'error discarding region %d~%d' % (offset, length)
raise make_ex(ret, msg)
@requires_not_closed
def write_zeroes(self, offset, length, zero_flags = 0):
"""
Zero the range from the image. By default it will attempt to
discard/unmap as much space as possible but any unaligned
extent segments will still be zeroed.
"""
cdef:
uint64_t _offset = offset, _length = length
int _zero_flags = zero_flags
with nogil:
ret = rbd_write_zeroes(self.image, _offset, _length,
_zero_flags, 0)
if ret < 0:
msg = 'error zeroing region %d~%d' % (offset, length)
raise make_ex(ret, msg)
@requires_not_closed
def flush(self):
"""
Block until all writes are fully flushed if caching is enabled.
"""
with nogil:
ret = rbd_flush(self.image)
if ret < 0:
raise make_ex(ret, 'error flushing image')
@requires_not_closed
def invalidate_cache(self):
"""
Drop any cached data for the image.
"""
with nogil:
ret = rbd_invalidate_cache(self.image)
if ret < 0:
raise make_ex(ret, 'error invalidating cache')
@requires_not_closed
def stripe_unit(self):
"""
Return the stripe unit used for the image.
"""
cdef uint64_t stripe_unit
with nogil:
ret = rbd_get_stripe_unit(self.image, &stripe_unit)
if ret != 0:
raise make_ex(ret, 'error getting stripe unit for image %s' % (self.name))
return stripe_unit
@requires_not_closed
def stripe_count(self):
"""
Return the stripe count used for the image.
"""
cdef uint64_t stripe_count
with nogil:
ret = rbd_get_stripe_count(self.image, &stripe_count)
if ret != 0:
raise make_ex(ret, 'error getting stripe count for image %s' % (self.name))
return stripe_count
@requires_not_closed
def create_timestamp(self):
"""
Return the create timestamp for the image.
"""
cdef:
timespec timestamp
with nogil:
ret = rbd_get_create_timestamp(self.image, ×tamp)
if ret != 0:
raise make_ex(ret, 'error getting create timestamp for image: %s' % (self.name))
return datetime.utcfromtimestamp(timestamp.tv_sec)
@requires_not_closed
def access_timestamp(self):
"""
Return the access timestamp for the image.
"""
cdef:
timespec timestamp
with nogil:
ret = rbd_get_access_timestamp(self.image, ×tamp)
if ret != 0:
raise make_ex(ret, 'error getting access timestamp for image: %s' % (self.name))
return datetime.fromtimestamp(timestamp.tv_sec)
@requires_not_closed
def modify_timestamp(self):
"""
Return the modify timestamp for the image.
"""
cdef:
timespec timestamp
with nogil:
ret = rbd_get_modify_timestamp(self.image, ×tamp)
if ret != 0:
raise make_ex(ret, 'error getting modify timestamp for image: %s' % (self.name))
return datetime.fromtimestamp(timestamp.tv_sec)
@requires_not_closed
def flatten(self, on_progress=None):
"""
Flatten clone image (copy all blocks from parent to child)
:param on_progress: optional progress callback function
:type on_progress: callback function
"""
cdef:
librbd_progress_fn_t _prog_cb = &no_op_progress_callback
void *_prog_arg = NULL
if on_progress:
_prog_cb = &progress_callback
_prog_arg = <void *>on_progress
with nogil:
ret = rbd_flatten_with_progress(self.image, _prog_cb, _prog_arg)
if ret < 0:
raise make_ex(ret, "error flattening %s" % self.name)
@requires_not_closed
def sparsify(self, sparse_size):
"""
Reclaim space for zeroed image extents
"""
cdef:
size_t _sparse_size = sparse_size
with nogil:
ret = rbd_sparsify(self.image, _sparse_size)
if ret < 0:
raise make_ex(ret, "error sparsifying %s" % self.name)
@requires_not_closed
def rebuild_object_map(self):
"""
Rebuild the object map for the image HEAD or currently set snapshot
"""
cdef librbd_progress_fn_t prog_cb = &no_op_progress_callback
with nogil:
ret = rbd_rebuild_object_map(self.image, prog_cb, NULL)
if ret < 0:
raise make_ex(ret, "error rebuilding object map %s" % self.name)
@requires_not_closed
def list_children(self):
"""
List children of the currently set snapshot (set via set_snap()).
:returns: list - a list of (pool name, image name) tuples
"""
cdef:
rbd_linked_image_spec_t *children = NULL
size_t num_children = 10
try:
while True:
children = <rbd_linked_image_spec_t*>realloc_chk(
children, num_children * sizeof(rbd_linked_image_spec_t))
with nogil:
ret = rbd_list_children3(self.image, children,
&num_children)
if ret >= 0:
break
elif ret != -errno.ERANGE:
raise make_ex(ret, 'error listing children.')
return [(decode_cstr(x.pool_name), decode_cstr(x.image_name)) for x
in children[:num_children] if not x.trash]
finally:
if children:
rbd_linked_image_spec_list_cleanup(children, num_children)
free(children)
@requires_not_closed
def list_children2(self):
"""
Iterate over the children of the image or its snapshot.
:returns: :class:`ChildIterator`
"""
return ChildIterator(self)
@requires_not_closed
def list_descendants(self):
"""
Iterate over the descendants of the image.
:returns: :class:`ChildIterator`
"""
return ChildIterator(self, True)
@requires_not_closed
def list_lockers(self):
"""
List clients that have locked the image and information
about the lock.
:returns: dict - contains the following keys:
* ``tag`` - the tag associated with the lock (every
additional locker must use the same tag)
* ``exclusive`` - boolean indicating whether the
lock is exclusive or shared
* ``lockers`` - a list of (client, cookie, address)
tuples
"""
cdef:
size_t clients_size = 512, cookies_size = 512
size_t addrs_size = 512, tag_size = 512
int exclusive = 0
char *c_clients = NULL
char *c_cookies = NULL
char *c_addrs = NULL
char *c_tag = NULL
try:
while True:
c_clients = <char *>realloc_chk(c_clients, clients_size)
c_cookies = <char *>realloc_chk(c_cookies, cookies_size)
c_addrs = <char *>realloc_chk(c_addrs, addrs_size)
c_tag = <char *>realloc_chk(c_tag, tag_size)
with nogil:
ret = rbd_list_lockers(self.image, &exclusive,
c_tag, &tag_size,
c_clients, &clients_size,
c_cookies, &cookies_size,
c_addrs, &addrs_size)
if ret >= 0:
break
elif ret != -errno.ERANGE:
raise make_ex(ret, 'error listing images')
if ret == 0:
return []
clients = map(decode_cstr, c_clients[:clients_size - 1].split(b'\0'))
cookies = map(decode_cstr, c_cookies[:cookies_size - 1].split(b'\0'))
addrs = map(decode_cstr, c_addrs[:addrs_size - 1].split(b'\0'))
return {
'tag' : decode_cstr(c_tag),
'exclusive' : exclusive == 1,
'lockers' : list(zip(clients, cookies, addrs)),
}
finally:
free(c_clients)
free(c_cookies)
free(c_addrs)
free(c_tag)
@requires_not_closed
def lock_acquire(self, lock_mode):
"""
Acquire a managed lock on the image.
:param lock_mode: lock mode to set
:type lock_mode: int
:raises: :class:`ImageBusy` if the lock could not be acquired
"""
cdef:
rbd_lock_mode_t _lock_mode = lock_mode
with nogil:
ret = rbd_lock_acquire(self.image, _lock_mode)
if ret < 0:
raise make_ex(ret, 'error acquiring lock on image')
@requires_not_closed
def lock_release(self):
"""
Release a managed lock on the image that was previously acquired.
"""
with nogil:
ret = rbd_lock_release(self.image)
if ret < 0:
raise make_ex(ret, 'error releasing lock on image')
@requires_not_closed
def lock_get_owners(self):
"""
Iterate over the lock owners of an image.
:returns: :class:`LockOwnerIterator`
"""
return LockOwnerIterator(self)
@requires_not_closed
def lock_break(self, lock_mode, lock_owner):
"""
Break the image lock held by a another client.
:param lock_owner: the owner of the lock to break
:type lock_owner: str
"""
lock_owner = cstr(lock_owner, 'lock_owner')
cdef:
rbd_lock_mode_t _lock_mode = lock_mode
char *_lock_owner = lock_owner
with nogil:
ret = rbd_lock_break(self.image, _lock_mode, _lock_owner)
if ret < 0:
raise make_ex(ret, 'error breaking lock on image')
@requires_not_closed
def lock_exclusive(self, cookie):
"""
Take an exclusive lock on the image.
:raises: :class:`ImageBusy` if a different client or cookie locked it
:class:`ImageExists` if the same client and cookie locked it
"""
cookie = cstr(cookie, 'cookie')
cdef char *_cookie = cookie
with nogil:
ret = rbd_lock_exclusive(self.image, _cookie)
if ret < 0:
raise make_ex(ret, 'error acquiring exclusive lock on image')
@requires_not_closed
def lock_shared(self, cookie, tag):
"""
Take a shared lock on the image. The tag must match
that of the existing lockers, if any.
:raises: :class:`ImageBusy` if a different client or cookie locked it
:class:`ImageExists` if the same client and cookie locked it
"""
cookie = cstr(cookie, 'cookie')
tag = cstr(tag, 'tag')
cdef:
char *_cookie = cookie
char *_tag = tag
with nogil:
ret = rbd_lock_shared(self.image, _cookie, _tag)
if ret < 0:
raise make_ex(ret, 'error acquiring shared lock on image')
@requires_not_closed
def unlock(self, cookie):
"""
Release a lock on the image that was locked by this rados client.
"""
cookie = cstr(cookie, 'cookie')
cdef char *_cookie = cookie
with nogil:
ret = rbd_unlock(self.image, _cookie)
if ret < 0:
raise make_ex(ret, 'error unlocking image')
@requires_not_closed
def break_lock(self, client, cookie):
"""
Release a lock held by another rados client.
"""
client = cstr(client, 'client')
cookie = cstr(cookie, 'cookie')
cdef:
char *_client = client
char *_cookie = cookie
with nogil:
ret = rbd_break_lock(self.image, _client, _cookie)
if ret < 0:
raise make_ex(ret, 'error unlocking image')
@requires_not_closed
def mirror_image_enable(self, mode=RBD_MIRROR_IMAGE_MODE_JOURNAL):
"""
Enable mirroring for the image.
"""
cdef rbd_mirror_image_mode_t c_mode = mode
with nogil:
ret = rbd_mirror_image_enable2(self.image, c_mode)
if ret < 0:
raise make_ex(ret, 'error enabling mirroring for image %s' % self.name)
@requires_not_closed
def mirror_image_disable(self, force):
"""
Disable mirroring for the image.
:param force: force disabling
:type force: bool
"""
cdef bint c_force = force
with nogil:
ret = rbd_mirror_image_disable(self.image, c_force)
if ret < 0:
raise make_ex(ret, 'error disabling mirroring for image %s' % self.name)
@requires_not_closed
def mirror_image_promote(self, force):
"""
Promote the image to primary for mirroring.
:param force: force promoting
:type force: bool
"""
cdef bint c_force = force
with nogil:
ret = rbd_mirror_image_promote(self.image, c_force)
if ret < 0:
raise make_ex(ret, 'error promoting image %s to primary' % self.name)
@requires_not_closed
def mirror_image_demote(self):
"""
Demote the image to secondary for mirroring.
"""
with nogil:
ret = rbd_mirror_image_demote(self.image)
if ret < 0:
raise make_ex(ret, 'error demoting image %s to secondary' % self.name)
@requires_not_closed
def mirror_image_resync(self):
"""
Flag the image to resync.
"""
with nogil:
ret = rbd_mirror_image_resync(self.image)
if ret < 0:
raise make_ex(ret, 'error to resync image %s' % self.name)
@requires_not_closed
def mirror_image_create_snapshot(self, flags=0):
"""
Create mirror snapshot.
:param flags: create snapshot flags
:type flags: int
:returns: int - the snapshot Id
"""
cdef:
uint32_t _flags = flags
uint64_t snap_id
with nogil:
ret = rbd_mirror_image_create_snapshot2(self.image, _flags,
&snap_id)
if ret < 0:
raise make_ex(ret, 'error creating mirror snapshot for image %s' %
self.name)
return snap_id
@requires_not_closed
def aio_mirror_image_create_snapshot(self, flags, oncomplete):
"""
Asynchronously create mirror snapshot.
Raises :class:`InvalidArgument` if the image is not in mirror
snapshot mode.
oncomplete will be called with the created snap ID as
well as the completion:
oncomplete(completion, snap_id)
:param flags: create snapshot flags
:type flags: int
:param oncomplete: what to do when the read is complete
:type oncomplete: completion
:returns: :class:`Completion` - the completion object
:raises: :class:`InvalidArgument`
"""
cdef:
uint32_t _flags = flags
Completion completion
def oncomplete_(completion_v):
cdef Completion _completion_v = completion_v
return_value = _completion_v.get_return_value()
snap_id = <object>(<uint64_t *>_completion_v.buf)[0] \
if return_value >= 0 else None
return oncomplete(_completion_v, snap_id)
completion = self.__get_completion(oncomplete_)
completion.buf = PyBytes_FromStringAndSize(NULL, sizeof(uint64_t))
try:
completion.__persist()
with nogil:
ret = rbd_aio_mirror_image_create_snapshot(self.image, _flags,
<uint64_t *>completion.buf,
completion.rbd_comp)
if ret < 0:
raise make_ex(ret, 'error creating mirror snapshot for image %s' %
self.name)
except:
completion.__unpersist()
raise
return completion
@requires_not_closed
def mirror_image_get_info(self):
"""
Get mirror info for the image.
:returns: dict - contains the following keys:
* ``global_id`` (str) - image global id
* ``state`` (int) - mirror state
* ``primary`` (bool) - is image primary
"""
cdef rbd_mirror_image_info_t c_info
with nogil:
ret = rbd_mirror_image_get_info(self.image, &c_info, sizeof(c_info))
if ret != 0:
raise make_ex(ret, 'error getting mirror info for image %s' % self.name)
info = {
'global_id' : decode_cstr(c_info.global_id),
'state' : int(c_info.state),
'primary' : c_info.primary,
}
rbd_mirror_image_get_info_cleanup(&c_info)
return info
@requires_not_closed
def aio_mirror_image_get_info(self, oncomplete):
"""
Asynchronously get mirror info for the image.
oncomplete will be called with the returned info as
well as the completion:
oncomplete(completion, info)
:param oncomplete: what to do when get info is complete
:type oncomplete: completion
:returns: :class:`Completion` - the completion object
"""
cdef:
Completion completion
def oncomplete_(completion_v):
cdef:
Completion _completion_v = completion_v
rbd_mirror_image_info_t *c_info = <rbd_mirror_image_info_t *>_completion_v.buf
info = {
'global_id' : decode_cstr(c_info[0].global_id),
'state' : int(c_info[0].state),
'primary' : c_info[0].primary,
}
rbd_mirror_image_get_info_cleanup(c_info)
return oncomplete(_completion_v, info)
completion = self.__get_completion(oncomplete_)
completion.buf = PyBytes_FromStringAndSize(
NULL, sizeof(rbd_mirror_image_info_t))
try:
completion.__persist()
with nogil:
ret = rbd_aio_mirror_image_get_info(
self.image, <rbd_mirror_image_info_t *>completion.buf,
sizeof(rbd_mirror_image_info_t), completion.rbd_comp)
if ret != 0:
raise make_ex(
ret, 'error getting mirror info for image %s' % self.name)
except:
completion.__unpersist()
raise
return completion
@requires_not_closed
def mirror_image_get_mode(self):
"""
Get mirror mode for the image.
:returns: int - mirror mode
"""
cdef rbd_mirror_image_mode_t c_mode
with nogil:
ret = rbd_mirror_image_get_mode(self.image, &c_mode)
if ret != 0:
raise make_ex(ret, 'error getting mirror mode for image %s' % self.name)
return int(c_mode)
@requires_not_closed
def aio_mirror_image_get_mode(self, oncomplete):
"""
Asynchronously get mirror mode for the image.
oncomplete will be called with the returned mode as
well as the completion:
oncomplete(completion, mode)
:param oncomplete: what to do when get info is complete
:type oncomplete: completion
:returns: :class:`Completion` - the completion object
"""
cdef:
Completion completion
def oncomplete_(completion_v):
cdef Completion _completion_v = completion_v
return_value = _completion_v.get_return_value()
mode = int((<rbd_mirror_image_mode_t *>_completion_v.buf)[0]) \
if return_value >= 0 else None
return oncomplete(_completion_v, mode)
completion = self.__get_completion(oncomplete_)
completion.buf = PyBytes_FromStringAndSize(
NULL, sizeof(rbd_mirror_image_mode_t))
try:
completion.__persist()
with nogil:
ret = rbd_aio_mirror_image_get_mode(
self.image, <rbd_mirror_image_mode_t *>completion.buf,
completion.rbd_comp)
if ret != 0:
raise make_ex(
ret, 'error getting mirror mode for image %s' % self.name)
except:
completion.__unpersist()
raise
return completion
@requires_not_closed
def mirror_image_get_status(self):
"""
Get mirror status for the image.
:returns: dict - contains the following keys:
* ``name`` (str) - mirror image name
* ``id`` (str) - mirror image id
* ``info`` (dict) - mirror image info
* ``state`` (int) - status mirror state
* ``description`` (str) - status description
* ``last_update`` (datetime) - last status update time
* ``up`` (bool) - is mirroring agent up
* ``remote_statuses`` (array) -
* ``mirror_uuid`` (str) - remote mirror uuid
* ``state`` (int) - status mirror state
* ``description`` (str) - status description
* ``last_update`` (datetime) - last status update time
* ``up`` (bool) - is mirroring agent up
"""
cdef:
rbd_mirror_image_site_status_t *s_status
rbd_mirror_image_global_status_t c_status
try:
with nogil:
ret = rbd_mirror_image_get_global_status(self.image, &c_status,
sizeof(c_status))
if ret != 0:
raise make_ex(ret, 'error getting mirror status for image %s' % self.name)
local_status = None
site_statuses = []
for i in range(c_status.site_statuses_count):
s_status = &c_status.site_statuses[i]
site_status = {
'state' : s_status.state,
'description' : decode_cstr(s_status.description),
'last_update' : datetime.utcfromtimestamp(s_status.last_update),
'up' : s_status.up,
}
mirror_uuid = decode_cstr(s_status.mirror_uuid)
if mirror_uuid == '':
local_status = site_status
else:
site_status['mirror_uuid'] = mirror_uuid
site_statuses.append(site_status)
status = {
'name': decode_cstr(c_status.name),
'id' : self.id(),
'info': {
'global_id' : decode_cstr(c_status.info.global_id),
'state' : int(c_status.info.state),
'primary' : c_status.info.primary,
},
'remote_statuses': site_statuses,
}
if local_status:
status.update(local_status)
finally:
rbd_mirror_image_global_status_cleanup(&c_status)
return status
@requires_not_closed
def mirror_image_get_instance_id(self):
"""
Get mirror instance id for the image.
:returns: str - instance id
"""
cdef:
int ret = -errno.ERANGE
size_t size = 32
char *instance_id = NULL
try:
while ret == -errno.ERANGE and size <= 4096:
instance_id = <char *>realloc_chk(instance_id, size)
with nogil:
ret = rbd_mirror_image_get_instance_id(self.image,
instance_id, &size)
if ret != 0:
raise make_ex(ret,
'error getting mirror instance id for image %s' %
self.name)
return decode_cstr(instance_id)
finally:
free(instance_id)
@requires_not_closed
def aio_read(self, offset, length, oncomplete, fadvise_flags=0):
"""
Asynchronously read data from the image
Raises :class:`InvalidArgument` if part of the range specified is
outside the image.
oncomplete will be called with the returned read value as
well as the completion:
oncomplete(completion, data_read)
:param offset: the offset to start reading at
:type offset: int
:param length: how many bytes to read
:type length: int
:param oncomplete: what to do when the read is complete
:type oncomplete: completion
:param fadvise_flags: fadvise flags for this read
:type fadvise_flags: int
:returns: :class:`Completion` - the completion object
:raises: :class:`InvalidArgument`, :class:`IOError`
"""
cdef:
char *ret_buf
uint64_t _offset = offset
size_t _length = length
int _fadvise_flags = fadvise_flags
Completion completion
def oncomplete_(completion_v):
cdef Completion _completion_v = completion_v
return_value = _completion_v.get_return_value()
if return_value > 0 and return_value != length:
_PyBytes_Resize(&_completion_v.buf, return_value)
return oncomplete(_completion_v, <object>_completion_v.buf if return_value >= 0 else None)
completion = self.__get_completion(oncomplete_)
completion.buf = PyBytes_FromStringAndSize(NULL, length)
ret_buf = PyBytes_AsString(completion.buf)
try:
completion.__persist()
with nogil:
ret = rbd_aio_read2(self.image, _offset, _length, ret_buf,
completion.rbd_comp, _fadvise_flags)
if ret < 0:
raise make_ex(ret, 'error reading %s %ld~%ld' %
(self.name, offset, length))
except:
completion.__unpersist()
raise
return completion
@requires_not_closed
def aio_write(self, data, offset, oncomplete, fadvise_flags=0):
"""
Asynchronously write data to the image
Raises :class:`InvalidArgument` if part of the write would fall outside
the image.
oncomplete will be called with the completion:
oncomplete(completion)
:param data: the data to be written
:type data: bytes
:param offset: the offset to start writing at
:type offset: int
:param oncomplete: what to do when the write is complete
:type oncomplete: completion
:param fadvise_flags: fadvise flags for this write
:type fadvise_flags: int
:returns: :class:`Completion` - the completion object
:raises: :class:`InvalidArgument`, :class:`IOError`
"""
cdef:
uint64_t _offset = offset
char *_data = data
size_t _length = len(data)
int _fadvise_flags = fadvise_flags
Completion completion
completion = self.__get_completion(oncomplete)
try:
completion.__persist()
with nogil:
ret = rbd_aio_write2(self.image, _offset, _length, _data,
completion.rbd_comp, _fadvise_flags)
if ret < 0:
raise make_ex(ret, 'error writing %s %ld~%ld' %
(self.name, offset, _length))
except:
completion.__unpersist()
raise
return completion
@requires_not_closed
def aio_discard(self, offset, length, oncomplete):
"""
Asynchronously trim the range from the image. It will be logically
filled with zeroes.
"""
cdef:
uint64_t _offset = offset
size_t _length = length
Completion completion
completion = self.__get_completion(oncomplete)
try:
completion.__persist()
with nogil:
ret = rbd_aio_discard(self.image, _offset, _length,
completion.rbd_comp)
if ret < 0:
raise make_ex(ret, 'error discarding %s %ld~%ld' %
(self.name, offset, _length))
except:
completion.__unpersist()
raise
return completion
@requires_not_closed
def aio_write_zeroes(self, offset, length, oncomplete, zero_flags = 0):
"""
Asynchronously Zero the range from the image. By default it will attempt
to discard/unmap as much space as possible but any unaligned extent
segments will still be zeroed.
"""
cdef:
uint64_t _offset = offset
size_t _length = length
int _zero_flags = zero_flags
Completion completion
completion = self.__get_completion(oncomplete)
try:
completion.__persist()
with nogil:
ret = rbd_aio_write_zeroes(self.image, _offset, _length,
completion.rbd_comp, _zero_flags, 0)
if ret < 0:
raise make_ex(ret, 'error zeroing %s %ld~%ld' %
(self.name, offset, length))
except:
completion.__unpersist()
raise
return completion
@requires_not_closed
def aio_flush(self, oncomplete):
"""
Asynchronously wait until all writes are fully flushed if caching is
enabled.
"""
cdef Completion completion = self.__get_completion(oncomplete)
try:
completion.__persist()
with nogil:
ret = rbd_aio_flush(self.image, completion.rbd_comp)
if ret < 0:
raise make_ex(ret, 'error flushing')
except:
completion.__unpersist()
raise
return completion
@requires_not_closed
def metadata_get(self, key):
"""
Get image metadata for the given key.
:param key: metadata key
:type key: str
:returns: str - metadata value
"""
key = cstr(key, 'key')
cdef:
char *_key = key
size_t size = 4096
char *value = NULL
int ret
try:
while True:
value = <char *>realloc_chk(value, size)
with nogil:
ret = rbd_metadata_get(self.image, _key, value, &size)
if ret != -errno.ERANGE:
break
if ret == -errno.ENOENT:
raise KeyError('no metadata %s for image %s' % (key, self.name))
if ret != 0:
raise make_ex(ret, 'error getting metadata %s for image %s' %
(key, self.name))
return decode_cstr(value)
finally:
free(value)
@requires_not_closed
def metadata_set(self, key, value):
"""
Set image metadata for the given key.
:param key: metadata key
:type key: str
:param value: metadata value
:type value: str
"""
key = cstr(key, 'key')
value = cstr(value, 'value')
cdef:
char *_key = key
char *_value = value
with nogil:
ret = rbd_metadata_set(self.image, _key, _value)
if ret != 0:
raise make_ex(ret, 'error setting metadata %s for image %s' %
(key, self.name))
@requires_not_closed
def metadata_remove(self, key):
"""
Remove image metadata for the given key.
:param key: metadata key
:type key: str
"""
key = cstr(key, 'key')
cdef:
char *_key = key
with nogil:
ret = rbd_metadata_remove(self.image, _key)
if ret == -errno.ENOENT:
raise KeyError('no metadata %s for image %s' % (key, self.name))
if ret != 0:
raise make_ex(ret, 'error removing metadata %s for image %s' %
(key, self.name))
@requires_not_closed
def metadata_list(self):
"""
List image metadata.
:returns: :class:`MetadataIterator`
"""
return MetadataIterator(self)
@requires_not_closed
def watchers_list(self):
"""
List image watchers.
:returns: :class:`WatcherIterator`
"""
return WatcherIterator(self)
@requires_not_closed
def config_list(self):
"""
List image-level config overrides.
:returns: :class:`ConfigImageIterator`
"""
return ConfigImageIterator(self)
@requires_not_closed
def config_set(self, key, value):
"""
Set an image-level configuration override.
:param key: key
:type key: str
:param value: value
:type value: str
"""
conf_key = 'conf_' + key
conf_key = cstr(conf_key, 'key')
value = cstr(value, 'value')
cdef:
char *_key = conf_key
char *_value = value
with nogil:
ret = rbd_metadata_set(self.image, _key, _value)
if ret != 0:
raise make_ex(ret, 'error setting config %s for image %s' %
(key, self.name))
@requires_not_closed
def config_get(self, key):
"""
Get an image-level configuration override.
:param key: key
:type key: str
:returns: str - value
"""
conf_key = 'conf_' + key
conf_key = cstr(conf_key, 'key')
cdef:
char *_key = conf_key
size_t size = 4096
char *value = NULL
int ret
try:
while True:
value = <char *>realloc_chk(value, size)
with nogil:
ret = rbd_metadata_get(self.image, _key, value, &size)
if ret != -errno.ERANGE:
break
if ret == -errno.ENOENT:
raise KeyError('no config %s for image %s' % (key, self.name))
if ret != 0:
raise make_ex(ret, 'error getting config %s for image %s' %
(key, self.name))
return decode_cstr(value)
finally:
free(value)
@requires_not_closed
def config_remove(self, key):
"""
Remove an image-level configuration override.
:param key: key
:type key: str
"""
conf_key = 'conf_' + key
conf_key = cstr(conf_key, 'key')
cdef:
char *_key = conf_key
with nogil:
ret = rbd_metadata_remove(self.image, _key)
if ret == -errno.ENOENT:
raise KeyError('no config %s for image %s' % (key, self.name))
if ret != 0:
raise make_ex(ret, 'error removing config %s for image %s' %
(key, self.name))
@requires_not_closed
def snap_get_namespace_type(self, snap_id):
"""
Get the snapshot namespace type.
:param snap_id: the snapshot id of a snap shot
:type key: int
"""
cdef:
rbd_snap_namespace_type_t namespace_type
uint64_t _snap_id = snap_id
with nogil:
ret = rbd_snap_get_namespace_type(self.image, _snap_id, &namespace_type)
if ret != 0:
raise make_ex(ret, 'error getting snapshot namespace type for image: %s, snap_id: %d' % (self.name, snap_id))
return namespace_type
@requires_not_closed
def snap_get_group_namespace(self, snap_id):
"""
get the group namespace details.
:param snap_id: the snapshot id of the group snapshot
:type key: int
:returns: dict - contains the following keys:
* ``pool`` (int) - pool id
* ``name`` (str) - group name
* ``snap_name`` (str) - group snap name
"""
cdef:
rbd_snap_group_namespace_t group_namespace
uint64_t _snap_id = snap_id
with nogil:
ret = rbd_snap_get_group_namespace(self.image, _snap_id,
&group_namespace,
sizeof(rbd_snap_group_namespace_t))
if ret != 0:
raise make_ex(ret, 'error getting snapshot group namespace for image: %s, snap_id: %d' % (self.name, snap_id))
info = {
'pool' : group_namespace.group_pool,
'name' : decode_cstr(group_namespace.group_name),
'snap_name' : decode_cstr(group_namespace.group_snap_name)
}
rbd_snap_group_namespace_cleanup(&group_namespace,
sizeof(rbd_snap_group_namespace_t))
return info
@requires_not_closed
def snap_get_trash_namespace(self, snap_id):
"""
get the trash namespace details.
:param snap_id: the snapshot id of the trash snapshot
:type key: int
:returns: dict - contains the following keys:
* ``original_name`` (str) - original snap name
"""
cdef:
uint64_t _snap_id = snap_id
size_t _size = 512
char *_name = NULL
try:
while True:
_name = <char*>realloc_chk(_name, _size);
with nogil:
ret = rbd_snap_get_trash_namespace(self.image, _snap_id,
_name, _size)
if ret >= 0:
break
elif ret != -errno.ERANGE:
raise make_ex(ret, 'error getting snapshot trash '
'namespace image: %s, snap_id: %d' % (self.name, snap_id))
return {
'original_name' : decode_cstr(_name)
}
finally:
free(_name)
@requires_not_closed
def snap_get_mirror_namespace(self, snap_id):
"""
get the mirror namespace details.
:param snap_id: the snapshot id of the mirror snapshot
:type key: int
:returns: dict - contains the following keys:
* ``state`` (int) - the snapshot state
* ``mirror_peer_uuids`` (list) - mirror peer uuids
* ``complete`` (bool) - True if snapshot is complete
* ``primary_mirror_uuid`` (str) - primary mirror uuid
* ``primary_snap_id`` (int) - primary snapshot Id
* ``last_copied_object_number`` (int) - last copied object number
"""
cdef:
rbd_snap_mirror_namespace_t sn
uint64_t _snap_id = snap_id
with nogil:
ret = rbd_snap_get_mirror_namespace(
self.image, _snap_id, &sn,
sizeof(rbd_snap_mirror_namespace_t))
if ret != 0:
raise make_ex(ret, 'error getting snapshot mirror '
'namespace for image: %s, snap_id: %d' %
(self.name, snap_id))
uuids = []
cdef char *p = sn.mirror_peer_uuids
for i in range(sn.mirror_peer_uuids_count):
uuid = decode_cstr(p)
uuids.append(uuid)
p += len(uuid) + 1
info = {
'state' : sn.state,
'mirror_peer_uuids' : uuids,
'complete' : sn.complete,
'primary_mirror_uuid' : decode_cstr(sn.primary_mirror_uuid),
'primary_snap_id' : sn.primary_snap_id,
'last_copied_object_number' : sn.last_copied_object_number,
}
rbd_snap_mirror_namespace_cleanup(
&sn, sizeof(rbd_snap_mirror_namespace_t))
return info
@requires_not_closed
def encryption_format(self, format, passphrase,
cipher_alg=RBD_ENCRYPTION_ALGORITHM_AES256):
passphrase = cstr(passphrase, "passphrase")
cdef rbd_encryption_format_t _format = format
cdef rbd_encryption_luks1_format_options_t _luks1_opts
cdef rbd_encryption_luks1_format_options_t _luks2_opts
cdef char* _passphrase = passphrase
if (format == RBD_ENCRYPTION_FORMAT_LUKS1):
_luks1_opts.alg = cipher_alg
_luks1_opts.passphrase = _passphrase
_luks1_opts.passphrase_size = len(passphrase)
with nogil:
ret = rbd_encryption_format(self.image, _format, &_luks1_opts,
sizeof(_luks1_opts))
if ret != 0:
raise make_ex(
ret,
'error formatting image %s with format luks1' % self.name)
elif (format == RBD_ENCRYPTION_FORMAT_LUKS2):
_luks2_opts.alg = cipher_alg
_luks2_opts.passphrase = _passphrase
_luks2_opts.passphrase_size = len(passphrase)
with nogil:
ret = rbd_encryption_format(self.image, _format, &_luks2_opts,
sizeof(_luks2_opts))
if ret != 0:
raise make_ex(
ret,
'error formatting image %s with format luks2' % self.name)
else:
raise make_ex(-errno.ENOTSUP, 'Unsupported encryption format')
@requires_not_closed
def encryption_load(self, format, passphrase):
passphrase = cstr(passphrase, "passphrase")
cdef rbd_encryption_format_t _format = format
cdef rbd_encryption_luks1_format_options_t _luks1_opts
cdef rbd_encryption_luks1_format_options_t _luks2_opts
cdef char* _passphrase = passphrase
if (format == RBD_ENCRYPTION_FORMAT_LUKS1):
_luks1_opts.passphrase = _passphrase
_luks1_opts.passphrase_size = len(passphrase)
with nogil:
ret = rbd_encryption_load(self.image, _format, &_luks1_opts,
sizeof(_luks1_opts))
if ret != 0:
raise make_ex(
ret,
('error loading encryption on image %s '
'with format luks1') % self.name)
elif (format == RBD_ENCRYPTION_FORMAT_LUKS2):
_luks2_opts.passphrase = _passphrase
_luks2_opts.passphrase_size = len(passphrase)
with nogil:
ret = rbd_encryption_load(self.image, _format, &_luks2_opts,
sizeof(_luks2_opts))
if ret != 0:
raise make_ex(
ret,
('error loading encryption on image %s '
'with format luks2') % self.name)
else:
raise make_ex(-errno.ENOTSUP, 'Unsupported encryption format')
cdef class ImageIterator(object):
"""
Iterator over RBD images in a pool
Yields a dictionary containing information about the images
Keys are:
* ``id`` (str) - image id
* ``name`` (str) - image name
"""
cdef rados_ioctx_t ioctx
cdef rbd_image_spec_t *images
cdef size_t num_images
def __init__(self, ioctx):
self.ioctx = convert_ioctx(ioctx)
self.images = NULL
self.num_images = 1024
while True:
self.images = <rbd_image_spec_t*>realloc_chk(
self.images, self.num_images * sizeof(rbd_image_spec_t))
with nogil:
ret = rbd_list2(self.ioctx, self.images, &self.num_images)
if ret >= 0:
break
elif ret == -errno.ERANGE:
self.num_images *= 2
else:
raise make_ex(ret, 'error listing images.')
def __iter__(self):
for i in range(self.num_images):
yield {
'id' : decode_cstr(self.images[i].id),
'name' : decode_cstr(self.images[i].name)
}
def __dealloc__(self):
if self.images:
rbd_image_spec_list_cleanup(self.images, self.num_images)
free(self.images)
cdef class LockOwnerIterator(object):
"""
Iterator over managed lock owners for an image
Yields a dictionary containing information about the image's lock
Keys are:
* ``mode`` (int) - active lock mode
* ``owner`` (str) - lock owner name
"""
cdef:
rbd_lock_mode_t lock_mode
char **lock_owners
size_t num_lock_owners
object image
def __init__(self, Image image):
image.require_not_closed()
self.image = image
self.lock_owners = NULL
self.num_lock_owners = 8
while True:
self.lock_owners = <char**>realloc_chk(self.lock_owners,
self.num_lock_owners *
sizeof(char*))
with nogil:
ret = rbd_lock_get_owners(image.image, &self.lock_mode,
self.lock_owners,
&self.num_lock_owners)
if ret >= 0:
break
elif ret == -errno.ENOENT:
self.num_lock_owners = 0
break
elif ret != -errno.ERANGE:
raise make_ex(ret, 'error listing lock owners for image %s' % image.name)
def __iter__(self):
for i in range(self.num_lock_owners):
yield {
'mode' : int(self.lock_mode),
'owner' : decode_cstr(self.lock_owners[i]),
}
def __dealloc__(self):
if self.lock_owners:
rbd_lock_get_owners_cleanup(self.lock_owners, self.num_lock_owners)
free(self.lock_owners)
cdef class MetadataIterator(object):
"""
Iterator over metadata list for an image.
Yields ``(key, value)`` tuple.
* ``key`` (str) - metadata key
* ``value`` (str) - metadata value
"""
cdef:
cdef object image
rbd_image_t c_image
char *last_read
uint64_t max_read
object next_chunk
def __init__(self, Image image):
image.require_not_closed()
self.image = image
self.c_image = image.image
self.last_read = strdup("")
self.max_read = 32
self.get_next_chunk()
def __iter__(self):
while len(self.next_chunk) > 0:
for pair in self.next_chunk:
yield pair
if len(self.next_chunk) < self.max_read:
break
self.get_next_chunk()
def __dealloc__(self):
if self.last_read:
free(self.last_read)
def get_next_chunk(self):
self.image.require_not_closed()
cdef:
char *c_keys = NULL
size_t keys_size = 4096
char *c_vals = NULL
size_t vals_size = 4096
try:
while True:
c_keys = <char *>realloc_chk(c_keys, keys_size)
c_vals = <char *>realloc_chk(c_vals, vals_size)
with nogil:
ret = rbd_metadata_list(self.c_image, self.last_read,
self.max_read, c_keys, &keys_size,
c_vals, &vals_size)
if ret >= 0:
break
elif ret != -errno.ERANGE:
raise make_ex(ret, 'error listing metadata for image %s' %
self.image.name)
keys = [decode_cstr(key) for key in
c_keys[:keys_size].split(b'\0') if key]
vals = [decode_cstr(val) for val in
c_vals[:vals_size].split(b'\0') if val]
if len(keys) > 0:
last_read = cstr(keys[-1], 'last_read')
free(self.last_read)
self.last_read = strdup(last_read)
self.next_chunk = list(zip(keys, vals))
finally:
free(c_keys)
free(c_vals)
cdef class SnapIterator(object):
"""
Iterator over snapshot info for an image.
Yields a dictionary containing information about a snapshot.
Keys are:
* ``id`` (int) - numeric identifier of the snapshot
* ``size`` (int) - size of the image at the time of snapshot (in bytes)
* ``name`` (str) - name of the snapshot
* ``namespace`` (int) - enum for snap namespace
* ``group`` (dict) - optional for group namespace snapshots
* ``trash`` (dict) - optional for trash namespace snapshots
* ``mirror`` (dict) - optional for mirror namespace snapshots
"""
cdef rbd_snap_info_t *snaps
cdef int num_snaps
cdef object image
def __init__(self, Image image):
image.require_not_closed()
self.image = image
self.snaps = NULL
self.num_snaps = 10
while True:
self.snaps = <rbd_snap_info_t*>realloc_chk(self.snaps,
self.num_snaps *
sizeof(rbd_snap_info_t))
with nogil:
ret = rbd_snap_list(image.image, self.snaps, &self.num_snaps)
if ret >= 0:
self.num_snaps = ret
break
elif ret != -errno.ERANGE:
raise make_ex(ret, 'error listing snapshots for image %s' % image.name)
def __iter__(self):
for i in range(self.num_snaps):
s = {
'id' : self.snaps[i].id,
'size' : self.snaps[i].size,
'name' : decode_cstr(self.snaps[i].name),
'namespace' : self.image.snap_get_namespace_type(self.snaps[i].id)
}
if s['namespace'] == RBD_SNAP_NAMESPACE_TYPE_GROUP:
try:
group = self.image.snap_get_group_namespace(self.snaps[i].id)
except:
group = None
s['group'] = group
elif s['namespace'] == RBD_SNAP_NAMESPACE_TYPE_TRASH:
try:
trash = self.image.snap_get_trash_namespace(self.snaps[i].id)
except:
trash = None
s['trash'] = trash
elif s['namespace'] == RBD_SNAP_NAMESPACE_TYPE_MIRROR:
try:
mirror = self.image.snap_get_mirror_namespace(
self.snaps[i].id)
except:
mirror = None
s['mirror'] = mirror
yield s
def __dealloc__(self):
if self.snaps:
rbd_snap_list_end(self.snaps)
free(self.snaps)
cdef class TrashIterator(object):
"""
Iterator over trash entries.
Yields a dictionary containing trash info of an image.
Keys are:
* `id` (str) - image id
* `name` (str) - image name
* `source` (str) - source of deletion
* `deletion_time` (datetime) - time of deletion
* `deferment_end_time` (datetime) - time that an image is allowed to be
removed from trash
"""
cdef:
rados_ioctx_t ioctx
size_t num_entries
rbd_trash_image_info_t *entries
def __init__(self, ioctx):
self.ioctx = convert_ioctx(ioctx)
self.num_entries = 1024
self.entries = NULL
while True:
self.entries = <rbd_trash_image_info_t*>realloc_chk(self.entries,
self.num_entries *
sizeof(rbd_trash_image_info_t))
with nogil:
ret = rbd_trash_list(self.ioctx, self.entries, &self.num_entries)
if ret >= 0:
self.num_entries = ret
break
elif ret != -errno.ERANGE:
raise make_ex(ret, 'error listing trash entries')
__source_string = ['USER', 'MIRRORING']
def __iter__(self):
for i in range(self.num_entries):
yield {
'id' : decode_cstr(self.entries[i].id),
'name' : decode_cstr(self.entries[i].name),
'source' : TrashIterator.__source_string[self.entries[i].source],
'deletion_time' : datetime.utcfromtimestamp(self.entries[i].deletion_time),
'deferment_end_time' : datetime.utcfromtimestamp(self.entries[i].deferment_end_time)
}
def __dealloc__(self):
rbd_trash_list_cleanup(self.entries, self.num_entries)
if self.entries:
free(self.entries)
cdef class ChildIterator(object):
"""
Iterator over child info for the image or its snapshot.
Yields a dictionary containing information about a child.
Keys are:
* ``pool`` (str) - name of the pool
* ``pool_namespace`` (str) - namespace of the pool
* ``image`` (str) - name of the child
* ``id`` (str) - id of the child
* ``trash`` (bool) - True if child is in trash bin
"""
cdef rbd_linked_image_spec_t *children
cdef size_t num_children
cdef object image
def __init__(self, Image image, descendants=False):
image.require_not_closed()
self.image = image
self.children = NULL
self.num_children = 10
while True:
self.children = <rbd_linked_image_spec_t*>realloc_chk(
self.children, self.num_children * sizeof(rbd_linked_image_spec_t))
if descendants:
with nogil:
ret = rbd_list_descendants(image.image, self.children,
&self.num_children)
else:
with nogil:
ret = rbd_list_children3(image.image, self.children,
&self.num_children)
if ret >= 0:
break
elif ret != -errno.ERANGE:
raise make_ex(ret, 'error listing children.')
def __iter__(self):
for i in range(self.num_children):
yield {
'pool' : decode_cstr(self.children[i].pool_name),
'pool_namespace' : decode_cstr(self.children[i].pool_namespace),
'image' : decode_cstr(self.children[i].image_name),
'id' : decode_cstr(self.children[i].image_id),
'trash' : self.children[i].trash
}
def __dealloc__(self):
if self.children:
rbd_linked_image_spec_list_cleanup(self.children, self.num_children)
free(self.children)
cdef class WatcherIterator(object):
"""
Iterator over watchers of an image.
Yields a dictionary containing information about a watcher.
Keys are:
* ``addr`` (str) - address of the watcher
* ``id`` (int) - id of the watcher
* ``cookie`` (int) - the watcher's cookie
"""
cdef rbd_image_watcher_t *watchers
cdef size_t num_watchers
cdef object image
def __init__(self, Image image):
image.require_not_closed()
self.image = image
self.watchers = NULL
self.num_watchers = 10
while True:
self.watchers = <rbd_image_watcher_t*>realloc_chk(self.watchers,
self.num_watchers *
sizeof(rbd_image_watcher_t))
with nogil:
ret = rbd_watchers_list(image.image, self.watchers, &self.num_watchers)
if ret >= 0:
break
elif ret != -errno.ERANGE:
raise make_ex(ret, 'error listing watchers.')
def __iter__(self):
for i in range(self.num_watchers):
yield {
'addr' : decode_cstr(self.watchers[i].addr),
'id' : self.watchers[i].id,
'cookie' : self.watchers[i].cookie
}
def __dealloc__(self):
if self.watchers:
rbd_watchers_list_cleanup(self.watchers, self.num_watchers)
free(self.watchers)
cdef class ConfigImageIterator(object):
"""
Iterator over image-level overrides for an image.
Yields a dictionary containing information about an override.
Keys are:
* ``name`` (str) - override name
* ``value`` (str) - override value
* ``source`` (str) - override source
"""
cdef:
rbd_config_option_t *options
int num_options
def __init__(self, Image image):
image.require_not_closed()
self.options = NULL
self.num_options = 32
while True:
self.options = <rbd_config_option_t *>realloc_chk(
self.options, self.num_options * sizeof(rbd_config_option_t))
with nogil:
ret = rbd_config_image_list(image.image, self.options,
&self.num_options)
if ret < 0:
if ret == -errno.ERANGE:
continue
self.num_options = 0
raise make_ex(ret, 'error listing config options')
break
def __iter__(self):
for i in range(self.num_options):
yield {
'name' : decode_cstr(self.options[i].name),
'value' : decode_cstr(self.options[i].value),
'source' : self.options[i].source,
}
def __dealloc__(self):
if self.options:
rbd_config_image_list_cleanup(self.options, self.num_options)
free(self.options)
cdef class GroupImageIterator(object):
"""
Iterator over image info for a group.
Yields a dictionary containing information about an image.
Keys are:
* ``name`` (str) - name of the image
* ``pool`` (int) - id of the pool this image belongs to
* ``state`` (int) - state of the image
"""
cdef rbd_group_image_info_t *images
cdef size_t num_images
cdef object group
def __init__(self, Group group):
self.group = group
self.images = NULL
self.num_images = 10
while True:
self.images = <rbd_group_image_info_t*>realloc_chk(self.images,
self.num_images *
sizeof(rbd_group_image_info_t))
with nogil:
ret = rbd_group_image_list(group._ioctx, group._name,
self.images,
sizeof(rbd_group_image_info_t),
&self.num_images)
if ret >= 0:
break
elif ret != -errno.ERANGE:
raise make_ex(ret, 'error listing images for group %s' % group.name, group_errno_to_exception)
def __iter__(self):
for i in range(self.num_images):
yield {
'name' : decode_cstr(self.images[i].name),
'pool' : self.images[i].pool,
'state' : self.images[i].state,
}
def __dealloc__(self):
if self.images:
rbd_group_image_list_cleanup(self.images,
sizeof(rbd_group_image_info_t),
self.num_images)
free(self.images)
cdef class GroupSnapIterator(object):
"""
Iterator over snaps specs for a group.
Yields a dictionary containing information about a snapshot.
Keys are:
* ``name`` (str) - name of the snapshot
* ``state`` (int) - state of the snapshot
"""
cdef rbd_group_snap_info_t *snaps
cdef size_t num_snaps
cdef object group
def __init__(self, Group group):
self.group = group
self.snaps = NULL
self.num_snaps = 10
while True:
self.snaps = <rbd_group_snap_info_t*>realloc_chk(self.snaps,
self.num_snaps *
sizeof(rbd_group_snap_info_t))
with nogil:
ret = rbd_group_snap_list(group._ioctx, group._name, self.snaps,
sizeof(rbd_group_snap_info_t),
&self.num_snaps)
if ret >= 0:
break
elif ret != -errno.ERANGE:
raise make_ex(ret, 'error listing snapshots for group %s' % group.name, group_errno_to_exception)
def __iter__(self):
for i in range(self.num_snaps):
yield {
'name' : decode_cstr(self.snaps[i].name),
'state' : self.snaps[i].state,
}
def __dealloc__(self):
if self.snaps:
rbd_group_snap_list_cleanup(self.snaps,
sizeof(rbd_group_snap_info_t),
self.num_snaps)
free(self.snaps)
|