Python librbd

安装librbd

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

  1. apt-get install -y python-ceph

创建Image

使用librbd创建Image也很简单,下面是示例代码。

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

也可以把下面代码保存成文件直接执行。

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

或者这样。

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