/usr/share/pyshared/rbd.py is in python-ceph 0.41-1ubuntu2.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 | """
This module is a thin wrapper around librbd.
It currently provides all the synchronous methods of librbd that do
not use callbacks.
Error codes from librbd are turned into exceptions that subclass
:class:`Error`. Almost all methods may raise :class:`Error`
(the base class of all rbd exceptions), :class:`PermissionError`
and :class:`IOError`, in addition to those documented for the
method.
A number of methods have string arguments, which must not be unicode
to interact correctly with librbd. If unicode is passed to these
methods, a :class:`TypeError` will be raised.
"""
# Copyright 2011 Josh Durgin
from ctypes import CDLL, c_char, c_char_p, c_size_t, c_void_p, c_int, \
create_string_buffer, byref, Structure, c_uint64
import ctypes
import errno
ANONYMOUS_AUID = 0xffffffffffffffff
ADMIN_AUID = 0
class Error(Exception):
pass
class PermissionError(Error):
pass
class ImageNotFound(Error):
pass
class ImageExists(Error):
pass
class IOError(Error):
pass
class NoSpace(Error):
pass
class IncompleteWriteError(Error):
pass
class InvalidArgument(Error):
pass
class LogicError(Error):
pass
class ReadOnlyImage(Error):
pass
class ImageBusy(Error):
pass
def make_ex(ret, msg):
"""
Translate a librbd return code into an exception.
:param ret: the return code
:type ret: int
:param msg: the error message to use
:type msg: str
:returns: a subclass of :class:`Error`
"""
errors = {
errno.EPERM : PermissionError,
errno.ENOENT : ImageNotFound,
errno.EIO : IOError,
errno.ENOSPC : NoSpace,
errno.EEXIST : ImageExists,
errno.EINVAL : InvalidArgument,
errno.EROFS : ReadOnlyImage,
errno.EBUSY : ImageBusy,
}
ret = abs(ret)
if ret in errors:
return errors[ret](msg)
else:
return Error(msg + (": error code %d" % ret))
class rbd_image_info_t(Structure):
_fields_ = [("size", c_uint64),
("obj_size", c_uint64),
("num_objs", c_uint64),
("order", c_int),
("block_name_prefix", c_char * 24),
("parent_pool", c_int),
("parent_name", c_char * 96)]
class rbd_snap_info_t(Structure):
_fields_ = [("id", c_uint64),
("size", c_uint64),
("name", c_char_p)]
class RBD(object):
"""
This class wraps librbd CRUD functions.
"""
def __init__(self):
self.librbd = CDLL('librbd.so.1')
def version(self):
"""
Get the version number of the ``librbd`` C library.
:returns: a tuple of ``(major, minor, extra)`` components of the
librbd version
"""
major = c_int(0)
minor = c_int(0)
extra = c_int(0)
self.librbd.rbd_version(byref(major), byref(minor), byref(extra))
return (major.value, minor.value, extra.value)
def create(self, ioctx, name, size, order=None):
"""
Create an rbd image.
:param ioctx: the context in which to create the image
:type ioctx: :class:`rados.Ioctx`
:param name: what the image is called
:type name: str
:param size: how big the image is in bytes
:type size: int
:param order: the image is split into (2**order) byte objects
:type order: int
:raises: :class:`ImageExists`
"""
if order is None:
order = 0
if not isinstance(name, str):
raise TypeError('name must be a string')
ret = self.librbd.rbd_create(ioctx.io, c_char_p(name), c_uint64(size),
byref(c_int(order)))
if ret < 0:
raise make_ex(ret, 'error creating image')
def list(self, ioctx):
"""
List image names.
:param ioctx: determines which RADOS pool is read
:type ioctx: :class:`rados.Ioctx`
:returns: list -- a list of image names
"""
size = c_size_t(512)
while True:
c_names = create_string_buffer(size.value)
ret = self.librbd.rbd_list(ioctx.io, byref(c_names), byref(size))
if ret >= 0:
break
elif ret != -errno.ERANGE:
raise make_ex(ret, 'error listing images')
return filter(lambda name: name != '', c_names.raw.split('\0'))
def remove(self, ioctx, name):
"""
Delete an RBD image. This may take a long time, since it does
not return until every object that comprises the image has
been deleted. Note that all snapshots must be deleted before
the image can be removed. If there are snapshots left,
:class:`ImageBusy` is raised.
:param ioctx: determines which RADOS pool the image is in
:type ioctx: :class:`rados.Ioctx`
:param name: the name of the image to remove
:type name: str
:raises: :class:`ImageNotFound`, :class:`ImageBusy`
"""
if not isinstance(name, str):
raise TypeError('name must be a string')
ret = self.librbd.rbd_remove(ioctx.io, c_char_p(name))
if ret != 0:
raise make_ex(ret, 'error removing image')
def rename(self, ioctx, src, dest):
"""
Rename an RBD image.
:param ioctx: determines which RADOS pool the image is in
:type ioctx: :class:`rados.Ioctx`
:param src: the current name of the image
:type src: str
:param dest: the new name of the image
:type dest: str
:raises: :class:`ImageNotFound`, :class:`ImageExists`
"""
if not isinstance(src, str) or not isinstance(dest, str):
raise TypeError('src and dest must be strings')
ret = self.librbd.rbd_rename(ioctx.io, c_char_p(src), c_char_p(dest))
if ret != 0:
raise make_ex(ret, 'error renaming image')
class Image(object):
"""
This class represents an RBD image. It is used to perform I/O on
the image and interact with snapshots.
**Note**: Any method of this class may raise :class:`ImageNotFound`
if the image has been deleted.
"""
def __init__(self, ioctx, name, snapshot=None):
"""
Open the image at the given snapshot.
If a snapshot is specified, the image will be read-only.
To clean up from opening the image, :func:`Image.close` should
be called. For ease of use, this is done automatically when
an :class:`Image` is used as a context manager (see :pep:`343`).
:param ioctx: determines which RADOS pool the image is in
:type ioctx: :class:`rados.Ioctx`
:param name: the name of the image
:type name: str
:param snapshot: which snapshot to read from
:type snaphshot: str
"""
self.librbd = CDLL('librbd.so.1')
self.image = c_void_p()
self.name = name
self.closed = False
if not isinstance(name, str):
raise TypeError('name must be a string')
if snapshot is not None and not isinstance(snapshot, str):
raise TypeError('snapshot must be a string or None')
ret = self.librbd.rbd_open(ioctx.io, c_char_p(name),
byref(self.image), c_char_p(snapshot))
if ret != 0:
raise make_ex(ret, 'error opening image %s at snapshot %s' % (name, snapshot))
def __enter__(self):
return self
def __exit__(self, type_, value, traceback):
"""
Closes the image. See :func:`close`
"""
self.close()
return False
def close(self):
"""
Release the resources used by this image object.
After this is called, this object should not be used.
"""
if not self.closed:
self.closed = True
self.librbd.rbd_close(self.image)
def __del__(self):
self.close()
def resize(self, size):
"""
Change the size of the image.
:param size: the new size of the image
:type size: int
"""
ret = self.librbd.rbd_resize(self.image, c_uint64(size))
if ret < 0:
raise make_ex(ret, 'error resizing image %s' % (self.name,))
def stat(self):
"""
Get information about the image. Currently parent pool and
parent name are always -1 and ''.
:returns: dict - contains the following keys:
* ``size`` (int) - the size of the image in bytes
* ``obj_size`` (int) - the size of each object that comprises the
image
* ``num_objs`` (int) - the number of objects in the image
* ``order`` (int) - log_2(object_size)
* ``block_name_prefix`` (str) - the prefix of the RADOS objects used
to store the image
* ``parent_pool`` (int) - parent pool id (-1 if no parent pool)
* ``parent_name`` (str) - name of parent pool ('' if no parent pool)
"""
info = rbd_image_info_t()
ret = self.librbd.rbd_stat(self.image, byref(info), ctypes.sizeof(info))
if ret != 0:
raise make_ex(ret, 'error getting info for image %s' % (self.name,))
return {
'size' : info.size,
'obj_size' : info.obj_size,
'num_objs' : info.num_objs,
'order' : info.order,
'block_name_prefix' : info.block_name_prefix,
'parent_pool' : info.parent_pool,
'parent_name' : info.parent_name,
}
def copy(self, dest_ioctx, dest_name):
"""
Copy the image to another location.
:param dest_ioctx: determines which pool to copy into
:type dest_ioctx: :class:`rados.Ioctx`
:param dest_name: the name of the copy
:type dest_name: str
:raises: :class:`ImageExists`
"""
if not isinstance(dest_name, str):
raise TypeError('dest_name must be a string')
ret = self.librbd.rbd_copy(self.image, dest_ioctx.io, c_char_p(dest_name))
if ret < 0:
raise make_ex(ret, 'error copying image %s to %s' % (self.name, dest_name))
def list_snaps(self):
"""
Iterate over the snapshots of an image.
:returns: :class:`SnapIterator`
"""
return SnapIterator(self)
def create_snap(self, name):
"""
Create a snapshot of the image.
:param name: the name of the snapshot
:type name: str
:raises: :class:`ImageExists`
"""
if not isinstance(name, str):
raise TypeError('name must be a string')
ret = self.librbd.rbd_snap_create(self.image, c_char_p(name))
if ret != 0:
raise make_ex(ret, 'error creating snapshot %s from %s' % (name, self.name))
def remove_snap(self, name):
"""
Delete a snapshot of the image.
:param name: the name of the snapshot
:type name: str
:raises: :class:`IOError`
"""
if not isinstance(name, str):
raise TypeError('name must be a string')
ret = self.librbd.rbd_snap_remove(self.image, c_char_p(name))
if ret != 0:
raise make_ex(ret, 'error removing snapshot %s from %s' % (name, self.name))
def rollback_to_snap(self, name):
"""
Revert the image to its contents at a snapshot. This is a
potentially expensive operation, since it rolls back each
object individually.
:param name: the snapshot to rollback to
:type name: str
:raises: :class:`IOError`
"""
if not isinstance(name, str):
raise TypeError('name must be a string')
ret = self.librbd.rbd_snap_rollback(self.image, c_char_p(name))
if ret != 0:
raise make_ex(ret, 'error rolling back image %s to snapshot %s' % (self.name, name))
def set_snap(self, name):
"""
Set the snapshot to read from. Writes will raise ReadOnlyImage
while a snapshot is set. Pass None to unset the snapshot
(reads come from the current image) , and allow writing again.
:param name: the snapshot to read from, or None to unset the snapshot
:type name: str or None
"""
if name is not None and not isinstance(name, str):
raise TypeError('name must be a string')
ret = self.librbd.rbd_snap_set(self.image, c_char_p(name))
if ret != 0:
raise make_ex(ret, 'error setting image %s to snapshot %s' % (self.name, name))
def read(self, offset, length):
"""
Read data from the image. Raises :class:`InvalidArgument` if
part of the range specified is outside the image.
:param offset: the offset to start reading at
:type offset: int
:param length: how many bytes to read
:type length: int
:returns: str - the data read
:raises: :class:`InvalidArgument`, :class:`IOError`
"""
ret_buf = create_string_buffer(length)
ret = self.librbd.rbd_read(self.image, c_uint64(offset),
c_size_t(length), byref(ret_buf))
if ret < 0:
raise make_ex(ret, 'error reading %s %ld~%ld' % (self.image, offset, length))
return ctypes.string_at(ret_buf, ret)
def write(self, data, offset):
"""
Write data to the image. Raises :class:`InvalidArgument` if
part of the write would fall outside the image.
:param data: the data to be written
:type data: str
:param offset: where to start writing data
:type offset: int
:returns: int - the number of bytes written
:raises: :class:`IncompleteWriteError`, :class:`LogicError`,
:class:`InvalidArgument`, :class:`IOError`
"""
if not isinstance(data, str):
raise TypeError('data must be a string')
length = len(data)
ret = self.librbd.rbd_write(self.image, c_uint64(offset),
c_size_t(length), c_char_p(data))
if ret == length:
return ret
elif ret < 0:
raise make_ex(ret, "error writing to %s" % (self.name,))
elif ret < length:
raise IncompleteWriteError("Wrote only %ld out of %ld bytes" % (ret, length))
else:
raise LogicError("logic error: rbd_write(%s) \
returned %d, but %d was the maximum number of bytes it could have \
written." % (self.name, ret, length))
class SnapIterator(object):
"""
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
"""
def __init__(self, image):
self.librbd = image.librbd
num_snaps = c_int(10)
while True:
self.snaps = (rbd_snap_info_t * num_snaps.value)()
ret = self.librbd.rbd_snap_list(image.image, byref(self.snaps),
byref(num_snaps))
if ret >= 0:
self.num_snaps = ret
break
elif ret != -errno.ERANGE:
raise make_ex(ret, 'error listing snapshots for image %s' % (image.name,))
def __iter__(self):
for i in xrange(self.num_snaps):
yield {
'id' : self.snaps[i].id,
'size' : self.snaps[i].size,
'name' : self.snaps[i].name,
}
def __del__(self):
self.librbd.rbd_snap_list_end(self.snaps)
|