]>
Commit | Line | Data |
---|---|---|
7c673cae FG |
1 | ================ |
2 | Librbd (Python) | |
3 | ================ | |
4 | ||
5 | .. highlight:: python | |
6 | ||
7 | The `rbd` python module provides file-like access to RBD images. | |
8 | ||
9 | ||
10 | Example: Creating and writing to an image | |
11 | ========================================= | |
12 | ||
13 | To use `rbd`, you must first connect to RADOS and open an IO | |
14 | context:: | |
15 | ||
16 | cluster = rados.Rados(conffile='my_ceph.conf') | |
17 | cluster.connect() | |
18 | ioctx = cluster.open_ioctx('mypool') | |
19 | ||
20 | Then you instantiate an :class:rbd.RBD object, which you use to create the | |
21 | image:: | |
22 | ||
23 | rbd_inst = rbd.RBD() | |
24 | size = 4 * 1024**3 # 4 GiB | |
25 | rbd_inst.create(ioctx, 'myimage', size) | |
26 | ||
27 | To perform I/O on the image, you instantiate an :class:rbd.Image object:: | |
28 | ||
29 | image = rbd.Image(ioctx, 'myimage') | |
30 | data = 'foo' * 200 | |
31 | image.write(data, 0) | |
32 | ||
33 | This writes 'foo' to the first 600 bytes of the image. Note that data | |
34 | cannot be :type:unicode - `Librbd` does not know how to deal with | |
35 | characters wider than a :c:type:char. | |
36 | ||
c07f9fc5 | 37 | In the end, you will want to close the image, the IO context and the connection to RADOS:: |
7c673cae FG |
38 | |
39 | image.close() | |
40 | ioctx.close() | |
41 | cluster.shutdown() | |
42 | ||
43 | To be safe, each of these calls would need to be in a separate :finally | |
44 | block:: | |
45 | ||
46 | cluster = rados.Rados(conffile='my_ceph_conf') | |
47 | try: | |
48 | ioctx = cluster.open_ioctx('my_pool') | |
49 | try: | |
50 | rbd_inst = rbd.RBD() | |
51 | size = 4 * 1024**3 # 4 GiB | |
52 | rbd_inst.create(ioctx, 'myimage', size) | |
53 | image = rbd.Image(ioctx, 'myimage') | |
54 | try: | |
55 | data = 'foo' * 200 | |
56 | image.write(data, 0) | |
57 | finally: | |
58 | image.close() | |
59 | finally: | |
60 | ioctx.close() | |
61 | finally: | |
62 | cluster.shutdown() | |
63 | ||
64 | This can be cumbersome, so the :class:`Rados`, :class:`Ioctx`, and | |
65 | :class:`Image` classes can be used as context managers that close/shutdown | |
66 | automatically (see :pep:`343`). Using them as context managers, the | |
67 | above example becomes:: | |
68 | ||
69 | with rados.Rados(conffile='my_ceph.conf') as cluster: | |
70 | with cluster.open_ioctx('mypool') as ioctx: | |
71 | rbd_inst = rbd.RBD() | |
72 | size = 4 * 1024**3 # 4 GiB | |
73 | rbd_inst.create(ioctx, 'myimage', size) | |
74 | with rbd.Image(ioctx, 'myimage') as image: | |
75 | data = 'foo' * 200 | |
76 | image.write(data, 0) | |
77 | ||
78 | API Reference | |
79 | ============= | |
80 | ||
81 | .. automodule:: rbd | |
82 | :members: RBD, Image, SnapIterator |