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