Kissingwolf's Blog

Python librbd 创建RBD image的三种方式

安装python-ceph库

Ceph官方提供Python库来访问RBD,通过以下命令可以安装。

1
# yum install python-rbd python-rados -y

创建 Image

有三种可选的写法,个人推荐第三种

简单流程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import rados
import rbd
cluster = rados.Rados(conffile='/etc/ceph/ceph.conf')
cluster.connect()
ioctx = cluster.open_ioctx('rbd')
rbd_inst = rbd.RBD()
size = 1024**3
image_name = "test_image"
rbd_inst.create(ioctx, image_name, size)
image = rbd.Image(ioctx, image_name)
data = 'foo' * 200
image.write(data, 0)
image.close()
ioctx.close()
cluster.shutdown()

Try-Finally 方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import rados
import rbd
cluster = rados.Rados(conffile='/etc/ceph/ceph.conf')
try:
ioctx = cluster.open_ioctx('rbd')
try:
rbd_inst = rbd.RBD()
size = 1024**3
image_name = "test_image"
rbd_inst.create(ioctx, image_name, size)
image = rbd.Image(ioctx, image_name)
try:
data = 'foo' * 200
image.write(data, 0)
finally:
image.close()
finally:
ioctx.close()
finally:
cluster.shutdown()

With-As 方式

1
2
3
4
5
6
7
8
9
with rados.Rados(conffile='/etc/ceph/ceph.conf') as cluster:
with cluster.open_ioctx('rbd') as ioctx:
rbd_inst = rbd.RBD()
size = 1024**3
image_name = "test_image"
rbd_inst.create(ioctx, image_name, size)
with rbd.Image(ioctx, image_name) as image:
data = 'foo' * 200
image.write(data, 0)