第 6 章 使用 Ceph 块设备 Python 模块

rbd python 模块提供对 Ceph 块设备镜像的类文件访问。要使用此内置工具,请导入 rbdrados Python 模块。

先决条件

  • 一个正在运行的 Red Hat Ceph Storage 集群。
  • 节点的根级别访问权限。

流程

  1. 连接到 RADOS 并打开 IO 上下文:

    cluster = rados.Rados(conffile='my_ceph.conf')
    cluster.connect()
    ioctx = cluster.open_ioctx('mypool')
  2. 实例化一个 :class:rbd.RBD 对象,用于创建镜像:

    rbd_inst = rbd.RBD()
    size = 4 * 1024**3  # 4 GiB
    rbd_inst.create(ioctx, 'myimage', size)
  3. 要在镜像上执行 I/O,请实例化一个 :class:rbd.Image 对象:

    image = rbd.Image(ioctx, 'myimage')
    data = 'foo' * 200
    image.write(data, 0)

    这会将"foo"写入镜像的前 600 字节。请注意,数据不能是 :type:unicode - librbd 不知道如何处理比 :c:type:char 更宽的字符。

  4. 关闭镜像、IO 上下文和与 RADOS 的连接:

    image.close()
    ioctx.close()
    cluster.shutdown()

    为了安全起见,每个调用都必须位于单独的 :finally 中 :

    import rados
    import rbd
    
    cluster = rados.Rados(conffile='my_ceph_conf')
    try:
        ioctx = cluster.open_ioctx('my_pool')
        try:
            rbd_inst = rbd.RBD()
            size = 4 * 1024**3  # 4 GiB
            rbd_inst.create(ioctx, 'myimage', size)
            image = rbd.Image(ioctx, 'myimage')
            try:
                data = 'foo' * 200
                image.write(data, 0)
            finally:
                image.close()
        finally:
            ioctx.close()
    finally:
        cluster.shutdown()

    这可能会有问题,RadosIoctxImage 类可以用作自动关闭或关闭的上下文管理器。使用它们作为上下文管理器时,上述示例如下:

    with rados.Rados(conffile='my_ceph.conf') as cluster:
        with cluster.open_ioctx('mypool') as ioctx:
            rbd_inst = rbd.RBD()
            size = 4 * 1024**3  # 4 GiB
            rbd_inst.create(ioctx, 'myimage', size)
            with rbd.Image(ioctx, 'myimage') as image:
                data = 'foo' * 200
                image.write(data, 0)