Librbd 的 Python 接口

rbd 的 python 模块为 RBD 映像提供了类似文件的访问方法。

实例:创建一映像并写入

要使用 rbd ,必须先连接 RADOS 并打开一个 IO 上下文:

  1. cluster = rados.Rados(conffile='my_ceph.conf')
  2. cluster.connect()
  3. ioctx = cluster.open_ioctx('mypool')

然后实例化一个 :class:rbd.RBD 对象,用它来创建映像:

  1. rbd_inst = rbd.RBD()
  2. size = 4 * 1024**3 # 4 GiB
  3. rbd_inst.create(ioctx, 'myimage', size)

要在映像上进行 I/O 操作,需实例化 :class:rbd.Image 对象:

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

上面的代码向映像前面写入了 600 字节的 foo 字符串。注意数据不能是 :type:unicode , librbd 不知道如何处理大于 :c:type:char 宽度的字符。

最后,应该要关闭映像、 IO 上下文和 RADOS 的连接。

  1. image.close()
  2. ioctx.close()
  3. cluster.shutdown()

安全起见,每个调用都应该封装到单独的 :finally 块内。

  1. cluster = rados.Rados(conffile='my_ceph_conf')
  2. try:
  3. ioctx = cluster.open_ioctx('my_pool')
  4. try:
  5. rbd_inst = rbd.RBD()
  6. size = 4 * 1024**3 # 4 GiB
  7. rbd_inst.create(ioctx, 'myimage', size)
  8. image = rbd.Image(ioctx, 'myimage')
  9. try:
  10. data = 'foo' * 200
  11. image.write(data, 0)
  12. finally:
  13. image.close()
  14. finally:
  15. ioctx.close()
  16. finally:
  17. cluster.shutdown()

这样做有些繁琐,所以 RadosIoctxImage 类可以当上下文管理器来用,它能自动关闭(见 PEP 343 )。作为上下文管理器使用时,上面的例子可以写成:

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

API 参考

This module is a thin wrapper around librbd.

It currently provides all the synchronous methods of librbd that donot use callbacks.

Error codes from librbd are turned into exceptions that subclassError. Almost all methods may raise Error(the base class of all rbd exceptions), PermissionErrorand IOError, in addition to those documented for themethod.

  • _class _rbd.RBD
  • This class wraps librbd CRUD functions.

    • clone(self, p_ioctx, p_name, p_snapname, c_ioctx, c_name, features=0, order=None, stripe_unit=0, stripe_count=0)
    • Clone a parent rbd snapshot into a COW sparse child.

Parameters:

  1. - **p_ioctx** the parent context that represents the parent snap
  2. - **p_name** the parent image name
  3. - **p_snapname** the parent image snapshot name
  4. - **c_ioctx** the child context that represents the new clone
  5. - **c_name** the clone (child) name
  6. - **features** (_int_) bitmask of features to enable; if set, must include layering
  7. - **order** (_int_) the image is split into (2**order) byte objects
  8. - **stripe_unit** (_int_) stripe unit in bytes (default 0 for object size)
  9. - **stripe_count** (_int_) objects to stripe over before loopingRaises :

TypeErrorRaises :InvalidArgumentRaises :ImageExistsRaises :FunctionNotSupportedRaises :ArgumentOutOfRange

  • create(self, ioctx, name, size, order=None, old_format=True, features=0, stripe_unit=0, stripe_count=0)
  • Create an rbd image.

Parameters:

  1. - **ioctx** (rados.Ioctx) the context in which to create the image
  2. - **name** (_str_) what the image is called
  3. - **size** (_int_) how big the image is in bytes
  4. - **order** (_int_) the image is split into (2**order) byte objects
  5. - **old_format** (_bool_) whether to create an old-style image thatis accessible by old clients, but cantuse more advanced features like layering.
  6. - **features** (_int_) bitmask of features to enable
  7. - **stripe_unit** (_int_) stripe unit in bytes (default 0 for object size)
  8. - **stripe_count** (_int_) objects to stripe over before loopingRaises :

ImageExistsRaises :TypeErrorRaises :InvalidArgumentRaises :FunctionNotSupported

  • list(self, ioctx)
  • List image names.

Parameters:ioctx (rados.Ioctx) – determines which RADOS pool is readReturns:list – a list of image names

  • remove(self, ioctx, name)
  • Delete an RBD image. This may take a long time, since it doesnot return until every object that comprises the image hasbeen deleted. Note that all snapshots must be deleted beforethe image can be removed. If there are snapshots left,ImageHasSnapshots is raised. If the image is stillopen, or the watch from a crashed client has not expired,ImageBusy is raised.

Parameters:

  1. - **ioctx** (rados.Ioctx) determines which RADOS pool the image is in
  2. - **name** (_str_) the name of the image to removeRaises :

ImageNotFound, ImageBusy,ImageHasSnapshots

  • rename(self, ioctx, src, dest)
  • Rename an RBD image.

Parameters:

  1. - **ioctx** (rados.Ioctx) determines which RADOS pool the image is in
  2. - **src** (_str_) the current name of the image
  3. - **dest** (_str_) the new name of the imageRaises :

ImageNotFound, ImageExists

  • version(self)
  • Get the version number of the librbd C library.

Returns:a tuple of (major,minor,extra) components of thelibrbd version

  • _class _rbd.Image
  • Image(ioctx, name, snapshot=None, read_only=False)

This class represents an RBD image. It is used to perform I/O onthe image and interact with snapshots.

Note: Any method of this class may raise ImageNotFoundif the image has been deleted.

  • breaklock(_self, client, cookie)
  • Release a lock held by another rados client.

  • close(self)

  • Release the resources used by this image object.

After this is called, this object should not be used.

  • copy(self, dest_ioctx, dest_name, features=0, order=None, stripe_unit=0, stripe_count=0)
  • Copy the image to another location.

Parameters:

  1. - **dest_ioctx** (rados.Ioctx) determines which pool to copy into
  2. - **dest_name** (_str_) the name of the copy
  3. - **features** (_int_) bitmask of features to enable; if set, must include layering
  4. - **order** (_int_) the image is split into (2**order) byte objects
  5. - **stripe_unit** (_int_) stripe unit in bytes (default 0 for object size)
  6. - **stripe_count** (_int_) objects to stripe over before loopingRaises :

TypeErrorRaises :InvalidArgumentRaises :ImageExistsRaises :FunctionNotSupportedRaises :ArgumentOutOfRange

  • createsnap(_self, name)
  • Create a snapshot of the image.

Parameters:name (str) – the name of the snapshotRaises :ImageExists

  • diffiterate(_self, offset, length, from_snapshot, iterate_cb, include_parent=True, whole_object=False)
  • Iterate over the changed extents of an image.

This will call iterate_cb with three arguments:

(offset, length, exists)

where the changed extent starts at offset bytes, continues forlength bytes, and is full of data (if exists is True) or zeroes(if exists is False).

If from_snapshot is None, it is interpreted as the beginningof time and this generates all allocated extents.

The end version is whatever is currently selected (via set_snap)for the image.

iterate_cb may raise an exception, which will abort the diff and will bepropagated to the caller.

Raises InvalidArgument if from_snapshot is afterthe currently set snapshot.

Raises ImageNotFound if from_snapshot is not the nameof a snapshot of the image.

Parameters:

  1. - **offset** (_int_) start offset in bytes
  2. - **length** (_int_) size of region to report on, in bytes
  3. - **from_snapshot** (_str or None_) starting snapshot name, or None
  4. - **iterate_cb** (_function acception arguments for offset,length, and exists_) function to call for each extent
  5. - **include_parent** (_bool_) True if full history diff should include parent
  6. - **whole_object** (_bool_) True if diff extents should cover whole objectRaises :

InvalidArgument, IOError,ImageNotFound

  • discard(self, offset, length)
  • Trim the range from the image. It will be logically filledwith zeroes.

  • features(self)

  • Gets the features bitmask of the image.

Returns:int - the features bitmask of the image

  • flags(self)
  • Gets the flags bitmask of the image.

Returns:int - the flags bitmask of the image

  • flatten(self)
  • Flatten clone image (copy all blocks from parent to child)

  • flush(self)

  • Block until all writes are fully flushed if caching is enabled.

  • invalidatecache(_self)

  • Drop any cached data for the image.

  • isexclusive_lock_owner(_self)

  • Gets the status of the image exclusive lock.

Returns:bool - true if the image is exclusively locked

  • isprotected_snap(_self, name)
  • Find out whether a snapshot is protected from deletion.

Parameters:name (str) – the snapshot to checkReturns:bool - whether the snapshot is protectedRaises :IOError, ImageNotFound

  • listchildren(_self)
  • List children of the currently set snapshot (set via set_snap()).

Returns:list - a list of (pool name, image name) tuples

  • listlockers(_self)
  • List clients that have locked the image and informationabout the lock.

Returns:dict - contains the following keys:

  1. - tag - the tag associated with the lock (everyadditional locker must use the same tag)
  2. -
  3. - exclusive - boolean indicating whether the
  4. - lock is exclusive or shared
  5. - lockers - a list of (client, cookie, address)tuples
  • listsnaps(_self)
  • Iterate over the snapshots of an image.

Returns:SnapIterator

  • lockexclusive(_self, cookie)
  • Take an exclusive lock on the image.

Raises :ImageBusy if a different client or cookie locked itImageExists if the same client and cookie locked it

  • lockshared(_self, cookie, tag)
  • Take a shared lock on the image. The tag must matchthat of the existing lockers, if any.

Raises :ImageBusy if a different client or cookie locked itImageExists if the same client and cookie locked it

  • oldformat(_self)
  • Find out whether the image uses the old RBD format.

Returns:bool - whether the image uses the old RBD format

  • overlap(self)
  • Gets the number of overlapping bytes between the image and its parentimage. If open to a snapshot, returns the overlap between the snapshotand the parent image.

Returns:int - the overlap in bytesRaises :ImageNotFound if the image doesn’t have a parent

  • parentinfo(_self)
  • Get information about a cloned image’s parent (if any)

Returns:tuple - (poolname,imagename,snapshotname) componentsof the parent imageRaises :ImageNotFound if the image doesn’t have a parent

  • protectsnap(_self, name)
  • Mark a snapshot as protected. This means it can’t be deleteduntil it is unprotected.

Parameters:name (str) – the snapshot to protectRaises :IOError, ImageNotFound

  • read(self, offset, length, fadvise_flags=0)
  • Read data from the image. Raises InvalidArgument ifpart of the range specified is outside the image.

Parameters:

  1. - **offset** (_int_) the offset to start reading at
  2. - **length** (_int_) how many bytes to read
  3. - **fadvise_flags** (_int_) fadvise flags for this readReturns:

str - the data readRaises :InvalidArgument, IOError

  • rebuildobject_map(_self)
  • Rebuilds the object map for the image HEAD or currently set snapshot

  • removesnap(_self, name)

  • Delete a snapshot of the image.

Parameters:name (str) – the name of the snapshotRaises :IOError, ImageBusy

  • renamesnap(_self, srcname, dstname)
  • rename a snapshot of the image.

Parameters:

  1. - **srcname** (_str_) the src name of the snapshot
  2. - **dstname** (_str_) the dst name of the snapshotRaises :

ImageExists

  • resize(self, size)
  • Change the size of the image.

Parameters:size (int) – the new size of the image

  • rollbackto_snap(_self, name)
  • Revert the image to its contents at a snapshot. This is apotentially expensive operation, since it rolls back eachobject individually.

Parameters:name (str) – the snapshot to rollback toRaises :IOError

  • setsnap(_self, name)
  • Set the snapshot to read from. Writes will raise ReadOnlyImagewhile a snapshot is set. Pass None to unset the snapshot(reads come from the current image) , and allow writing again.

Parameters:name (str or None) – the snapshot to read from, or None to unset the snapshot

  • size(self)
  • Get the size of the image. If open to a snapshot, returns thesize of that snapshot.

Returns:the size of the image in bytes

  • stat(self)
  • Get information about the image. Currently parent pool andparent name are always -1 and ‘’.

Returns:dict - contains the following keys:

  1. - size (int) - the size of the image in bytes
  2. - obj_size (int) - the size of each object that comprises theimage
  3. - num_objs (int) - the number of objects in the image
  4. - order (int) - log_2(object_size)
  5. - block_name_prefix (str) - the prefix of the RADOS objects usedto store the image
  6. - parent_pool (int) - deprecated
  7. - parent_name (str) - deprecated

See also format() and features().

  • stripecount(_self)
  • Returns the stripe count used for the image.

  • stripeunit(_self)

  • Returns the stripe unit used for the image.

  • unlock(self, cookie)

  • Release a lock on the image that was locked by this rados client.

  • unprotectsnap(_self, name)

  • Mark a snapshot unprotected. This allows it to be deleted ifit was protected.

Parameters:name (str) – the snapshot to unprotectRaises :IOError, ImageNotFound

  • updatefeatures(_self, features, enabled)
  • Updates the features bitmask of the image by enabling/disablinga single feature. The feature must support the ability to bedynamically enabled/disabled.

Parameters:

  1. - **features** (_int_) feature bitmask to enable/disable
  2. - **enabled** (_bool_) whether to enable/disable the featureRaises :

InvalidArgument

  • write(self, data, offset, fadvise_flags=0)
  • Write data to the image. Raises InvalidArgument ifpart of the write would fall outside the image.

Parameters:

  1. - **data** (_bytes_) the data to be written
  2. - **offset** (_int_) where to start writing data
  3. - **fadvise_flags** (_int_) fadvise flags for this writeReturns:

int - the number of bytes writtenRaises :IncompleteWriteError, LogicError,InvalidArgument, IOError

  • _class _rbd.SnapIterator
  • SnapIterator(Image image)

Iterator over snapshot info for an image.

Yields a dictionary containing information about a snapshot.

Keys are:

  • id (int) - numeric identifier of the snapshot
  • size (int) - size of the image at the time of snapshot (in bytes)
  • name (str) - name of the snapshot