/usr/lib/python2.7/dist-packages/rados.py is in python-ceph 0.79-0ubuntu1.
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 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 | """
This module is a thin wrapper around librados.
Copyright 2011, Hannu Valtonen <hannu.valtonen@ormod.com>
"""
from ctypes import CDLL, c_char_p, c_size_t, c_void_p, c_char, c_int, c_long, \
c_ulong, create_string_buffer, byref, Structure, c_uint64, c_ubyte, \
pointer, CFUNCTYPE
from ctypes.util import find_library
import ctypes
import errno
import threading
import time
from datetime import datetime
ANONYMOUS_AUID = 0xffffffffffffffff
ADMIN_AUID = 0
class Error(Exception):
""" `Error` class, derived from `Exception` """
pass
class InterruptedOrTimeoutError(Error):
""" `InterruptedOrTimeoutError` class, derived from `Error` """
pass
class PermissionError(Error):
""" `PermissionError` class, derived from `Error` """
pass
class ObjectNotFound(Error):
""" `ObjectNotFound` class, derived from `Error` """
pass
class NoData(Error):
""" `NoData` class, derived from `Error` """
pass
class ObjectExists(Error):
""" `ObjectExists` class, derived from `Error` """
pass
class IOError(Error):
""" `IOError` class, derived from `Error` """
pass
class NoSpace(Error):
""" `NoSpace` class, derived from `Error` """
pass
class IncompleteWriteError(Error):
""" `IncompleteWriteError` class, derived from `Error` """
pass
class RadosStateError(Error):
""" `RadosStateError` class, derived from `Error` """
pass
class IoctxStateError(Error):
""" `IoctxStateError` class, derived from `Error` """
pass
class ObjectStateError(Error):
""" `ObjectStateError` class, derived from `Error` """
pass
class LogicError(Error):
""" `` class, derived from `Error` """
pass
class TimedOut(Error):
""" `TimedOut` class, derived from `Error` """
pass
def make_ex(ret, msg):
"""
Translate a librados 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 : ObjectNotFound,
errno.EIO : IOError,
errno.ENOSPC : NoSpace,
errno.EEXIST : ObjectExists,
errno.ENODATA : NoData,
errno.EINTR : InterruptedOrTimeoutError,
errno.ETIMEDOUT : TimedOut
}
ret = abs(ret)
if ret in errors:
return errors[ret](msg)
else:
return Error(msg + (": errno %s" % errno.errorcode[ret]))
class rados_pool_stat_t(Structure):
""" Usage information for a pool """
_fields_ = [("num_bytes", c_uint64),
("num_kb", c_uint64),
("num_objects", c_uint64),
("num_object_clones", c_uint64),
("num_object_copies", c_uint64),
("num_objects_missing_on_primary", c_uint64),
("num_objects_unfound", c_uint64),
("num_objects_degraded", c_uint64),
("num_rd", c_uint64),
("num_rd_kb", c_uint64),
("num_wr", c_uint64),
("num_wr_kb", c_uint64)]
class rados_cluster_stat_t(Structure):
""" Cluster-wide usage information """
_fields_ = [("kb", c_uint64),
("kb_used", c_uint64),
("kb_avail", c_uint64),
("num_objects", c_uint64)]
class Version(object):
""" Version information """
def __init__(self, major, minor, extra):
self.major = major
self.minor = minor
self.extra = extra
def __str__(self):
return "%d.%d.%d" % (self.major, self.minor, self.extra)
class RadosThread(threading.Thread):
def __init__(self, target, args=None):
self.args = args
self.target = target
threading.Thread.__init__(self)
def run(self):
self.retval = self.target(*self.args)
# time in seconds between each call to t.join() for child thread
POLL_TIME_INCR = 0.5
def run_in_thread(target, args, timeout=0):
import sys
interrupt = False
countdown = timeout
t = RadosThread(target, args)
# allow the main thread to exit (presumably, avoid a join() on this
# subthread) before this thread terminates. This allows SIGINT
# exit of a blocked call. See below.
t.daemon = True
t.start()
try:
# poll for thread exit
while t.is_alive():
t.join(POLL_TIME_INCR)
if timeout:
countdown = countdown - POLL_TIME_INCR
if countdown <= 0:
raise KeyboardInterrupt
t.join() # in case t exits before reaching the join() above
except KeyboardInterrupt:
# ..but allow SIGINT to terminate the waiting. Note: this
# relies on the Linux kernel behavior of delivering the signal
# to the main thread in preference to any subthread (all that's
# strictly guaranteed is that *some* thread that has the signal
# unblocked will receive it). But there doesn't seem to be
# any interface to create t with SIGINT blocked.
interrupt = True
if interrupt:
t.retval = -errno.EINTR
return t.retval
class Rados(object):
"""librados python wrapper"""
def require_state(self, *args):
"""
Checks if the Rados object is in a special state
:raises: RadosStateError
"""
for a in args:
if self.state == a:
return
raise RadosStateError("You cannot perform that operation on a \
Rados object in state %s." % (self.state))
def __init__(self, rados_id=None, name=None, clustername=None,
conf_defaults=None, conffile=None, conf=None, flags=0):
librados_path = find_library('rados')
if not librados_path:
#maybe find_library can not find it correctly on all platforms.
try:
self.librados = CDLL('librados.so.2')
except OSError as e:
raise EnvironmentError("Unable to load librados: %s" % e)
except:
raise Error("Unexpected error")
else:
self.librados = CDLL(librados_path)
self.cluster = c_void_p()
self.rados_id = rados_id
if rados_id is not None and not isinstance(rados_id, str):
raise TypeError('rados_id must be a string or None')
if conffile is not None and not isinstance(conffile, str):
raise TypeError('conffile must be a string or None')
if name is not None and not isinstance(name, str):
raise TypeError('name must be a string or None')
if clustername is not None and not isinstance(clustername, str):
raise TypeError('clustername must be a string or None')
if rados_id and name:
raise Error("Rados(): can't supply both rados_id and name")
if rados_id:
name = 'client.' + rados_id
if name is None:
name = 'client.admin'
if clustername is None:
clustername = 'ceph'
ret = run_in_thread(self.librados.rados_create2,
(byref(self.cluster), c_char_p(clustername),
c_char_p(name), c_uint64(flags)))
if ret != 0:
raise Error("rados_initialize failed with error code: %d" % ret)
self.state = "configuring"
# order is important: conf_defaults, then conffile, then conf
if conf_defaults:
for key, value in conf_defaults.iteritems():
self.conf_set(key, value)
if conffile is not None:
# read the default conf file when '' is given
if conffile == '':
conffile = None
self.conf_read_file(conffile)
if conf:
for key, value in conf.iteritems():
self.conf_set(key, value)
def shutdown(self):
"""
Disconnects from the cluster.
"""
if (self.__dict__.has_key("state") and self.state != "shutdown"):
run_in_thread(self.librados.rados_shutdown, (self.cluster,))
self.state = "shutdown"
def __enter__(self):
self.connect()
return self
def __exit__(self, type_, value, traceback):
self.shutdown()
return False
def __del__(self):
self.shutdown()
def version(self):
"""
Get the version number of the ``librados`` C library.
:returns: a tuple of ``(major, minor, extra)`` components of the
librados version
"""
major = c_int(0)
minor = c_int(0)
extra = c_int(0)
run_in_thread(self.librados.rados_version,
(byref(major), byref(minor), byref(extra)))
return Version(major.value, minor.value, extra.value)
def conf_read_file(self, path=None):
"""
Configure the cluster handle using a Ceph config file.
:param path: path to the config file
:type path: str
"""
self.require_state("configuring", "connected")
if path is not None and not isinstance(path, str):
raise TypeError('path must be a string')
ret = run_in_thread(self.librados.rados_conf_read_file,
(self.cluster, c_char_p(path)))
if (ret != 0):
raise make_ex(ret, "error calling conf_read_file")
def conf_parse_argv(self, args):
"""
Parse known arguments from args, and remove; returned
args contain only those unknown to ceph
"""
self.require_state("configuring", "connected")
if not args:
return
# create instances of arrays of c_char_p's, both len(args) long
# cretargs will always be a subset of cargs (perhaps identical)
cargs = (c_char_p * len(args))(*args)
cretargs = (c_char_p * len(args))()
ret = run_in_thread(self.librados.rados_conf_parse_argv_remainder,
(self.cluster, len(args), cargs, cretargs))
if ret:
raise make_ex(ret, "error calling conf_parse_argv_remainder")
# cretargs was allocated with fixed length; collapse return
# list to eliminate any missing args
retargs = [a for a in cretargs if a is not None]
return retargs
def conf_parse_env(self, var='CEPH_ARGS'):
"""
Parse known arguments from an environment variable, normally
CEPH_ARGS.
"""
self.require_state("configuring", "connected")
if not var:
return
ret = run_in_thread(self.librados.rados_conf_parse_env,
(self.cluster, c_char_p(var)))
if (ret != 0):
raise make_ex(ret, "error calling conf_parse_env")
def conf_get(self, option):
"""
Get the value of a configuration option
:param option: which option to read
:type option: str
:returns: str - value of the option or None
:raises: :class:`TypeError`
"""
self.require_state("configuring", "connected")
if not isinstance(option, str):
raise TypeError('option must be a string')
length = 20
while True:
ret_buf = create_string_buffer(length)
ret = run_in_thread(self.librados.rados_conf_get,
(self.cluster, c_char_p(option), ret_buf,
c_size_t(length)))
if (ret == 0):
return ret_buf.value
elif (ret == -errno.ENAMETOOLONG):
length = length * 2
elif (ret == -errno.ENOENT):
return None
else:
raise make_ex(ret, "error calling conf_get")
def conf_set(self, option, val):
"""
Set the value of a configuration option
:param option: which option to set
:type option: str
:param option: value of the option
:type option: str
:raises: :class:`TypeError`, :class:`ObjectNotFound`
"""
self.require_state("configuring", "connected")
if not isinstance(option, str):
raise TypeError('option must be a string')
if not isinstance(val, str):
raise TypeError('val must be a string')
ret = run_in_thread(self.librados.rados_conf_set,
(self.cluster, c_char_p(option), c_char_p(val)))
if (ret != 0):
raise make_ex(ret, "error calling conf_set")
def ping_monitor(self, mon_id):
"""
Ping a monitor to assess liveness
May be used as a simply way to assess liveness, or to obtain
informations about the monitor in a simple way even in the
absence of quorum.
:param mon_id: the ID portion of the monitor's name (i.e., mon.<ID>)
:type mon_id: str
:returns: the string reply from the monitor
"""
self.require_state("configuring", "connected")
outstrp = pointer(pointer(c_char()))
outstrlen = c_long()
ret = run_in_thread(self.librados.rados_ping_monitor,
(self.cluster, c_char_p(mon_id),
outstrp, byref(outstrlen)))
my_outstr = outstrp.contents[:(outstrlen.value)]
if outstrlen.value:
run_in_thread(self.librados.rados_buffer_free, (outstrp.contents,))
if ret != 0:
raise make_ex(ret, "error calling ping_monitor")
return my_outstr
def connect(self, timeout=0):
"""
Connect to the cluster.
"""
self.require_state("configuring")
ret = run_in_thread(self.librados.rados_connect, (self.cluster,),
timeout)
if (ret != 0):
raise make_ex(ret, "error calling connect")
self.state = "connected"
def get_cluster_stats(self):
"""
Read usage info about the cluster
This tells you total space, space used, space available, and number
of objects. These are not updated immediately when data is written,
they are eventually consistent.
:returns: dict - contains the following keys:
- ``kb`` (int) - total space
- ``kb_used`` (int) - space used
- ``kb_avail`` (int) - free space available
- ``num_objects`` (int) - number of objects
"""
stats = rados_cluster_stat_t()
ret = run_in_thread(self.librados.rados_cluster_stat,
(self.cluster, byref(stats)))
if ret < 0:
raise make_ex(
ret, "Rados.get_cluster_stats(%s): get_stats failed" % self.rados_id)
return {'kb': stats.kb,
'kb_used': stats.kb_used,
'kb_avail': stats.kb_avail,
'num_objects': stats.num_objects}
def pool_exists(self, pool_name):
"""
Checks if a given pool exists.
:param pool_name: name of the pool to check
:type pool_name: str
:raises: :class:`TypeError`, :class:`Error`
:returns: bool - whether the pool exists, false otherwise.
"""
self.require_state("connected")
if not isinstance(pool_name, str):
raise TypeError('pool_name must be a string')
ret = run_in_thread(self.librados.rados_pool_lookup,
(self.cluster, c_char_p(pool_name)))
if (ret >= 0):
return True
elif (ret == -errno.ENOENT):
return False
else:
raise make_ex(ret, "error looking up pool '%s'" % pool_name)
def create_pool(self, pool_name, auid=None, crush_rule=None):
"""
Create a pool:
- with default settings: if auid=None and crush_rule=None
- owned by a specific auid: auid given and crush_rule=None
- with a specific CRUSH rule: if auid=None and crush_rule given
- with a specific CRUSH rule and auid: if auid and crush_rule given
:param pool_name: name of the pool to create
:type pool_name: str
:param auid: the id of the owner of the new pool
:type auid: int
:param crush_rule: rule to use for placement in the new pool
:type crush_rule: str
:raises: :class:`TypeError`, :class:`Error`
"""
self.require_state("connected")
if not isinstance(pool_name, str):
raise TypeError('pool_name must be a string')
if crush_rule is not None and not isinstance(crush_rule, str):
raise TypeError('cruse_rule must be a string')
if (auid == None):
if (crush_rule == None):
ret = run_in_thread(self.librados.rados_pool_create,
(self.cluster, c_char_p(pool_name)))
else:
ret = run_in_thread(self.librados.\
rados_pool_create_with_crush_rule,
(self.cluster, c_char_p(pool_name),
c_ubyte(crush_rule)))
elif (crush_rule == None):
ret = run_in_thread(self.librados.rados_pool_create_with_auid,
(self.cluster, c_char_p(pool_name),
c_uint64(auid)))
else:
ret = run_in_thread(self.librados.rados_pool_create_with_all,
(self.cluster, c_char_p(pool_name),
c_uint64(auid), c_ubyte(crush_rule)))
if ret < 0:
raise make_ex(ret, "error creating pool '%s'" % pool_name)
def delete_pool(self, pool_name):
"""
Delete a pool and all data inside it.
The pool is removed from the cluster immediately,
but the actual data is deleted in the background.
:param pool_name: name of the pool to delete
:type pool_name: str
:raises: :class:`TypeError`, :class:`Error`
"""
self.require_state("connected")
if not isinstance(pool_name, str):
raise TypeError('pool_name must be a string')
ret = run_in_thread(self.librados.rados_pool_delete,
(self.cluster, c_char_p(pool_name)))
if ret < 0:
raise make_ex(ret, "error deleting pool '%s'" % pool_name)
def list_pools(self):
"""
Gets a list of pool names.
:returns: list - of pool names.
"""
self.require_state("connected")
size = c_size_t(512)
while True:
c_names = create_string_buffer(size.value)
ret = run_in_thread(self.librados.rados_pool_list,
(self.cluster, byref(c_names), size))
if ret > size.value:
size = c_size_t(ret)
else:
break
return filter(lambda name: name != '', c_names.raw.split('\0'))
def get_fsid(self):
"""
Get the fsid of the cluster as a hexadecimal string.
:raises: :class:`Error`
:returns: str - cluster fsid
"""
self.require_state("connected")
buf_len = 37
fsid = create_string_buffer(buf_len)
ret = run_in_thread(self.librados.rados_cluster_fsid,
(self.cluster, byref(fsid), c_size_t(buf_len)))
if ret < 0:
raise make_ex(ret, "error getting cluster fsid")
return fsid.value
def open_ioctx(self, ioctx_name):
"""
Create an io context
The io context allows you to perform operations within a particular
pool.
:param ioctx_name: name of the pool
:type ioctx_name: str
:raises: :class:`TypeError`, :class:`Error`
:returns: Ioctx - Rados Ioctx object
"""
self.require_state("connected")
if not isinstance(ioctx_name, str):
raise TypeError('ioctx_name must be a string')
ioctx = c_void_p()
ret = run_in_thread(self.librados.rados_ioctx_create,
(self.cluster, c_char_p(ioctx_name), byref(ioctx)))
if ret < 0:
raise make_ex(ret, "error opening ioctx '%s'" % ioctx_name)
return Ioctx(ioctx_name, self.librados, ioctx)
def mon_command(self, cmd, inbuf, timeout=0, target=None):
"""
mon_command[_target](cmd, inbuf, outbuf, outbuflen, outs, outslen)
returns (int ret, string outbuf, string outs)
"""
import sys
self.require_state("connected")
outbufp = pointer(pointer(c_char()))
outbuflen = c_long()
outsp = pointer(pointer(c_char()))
outslen = c_long()
cmdarr = (c_char_p * len(cmd))(*cmd)
if target:
ret = run_in_thread(self.librados.rados_mon_command_target,
(self.cluster, c_char_p(target), cmdarr,
len(cmd), c_char_p(inbuf), len(inbuf),
outbufp, byref(outbuflen), outsp,
byref(outslen)), timeout)
else:
ret = run_in_thread(self.librados.rados_mon_command,
(self.cluster, cmdarr, len(cmd),
c_char_p(inbuf), len(inbuf),
outbufp, byref(outbuflen), outsp, byref(outslen)),
timeout)
# copy returned memory (ctypes makes a copy, not a reference)
my_outbuf = outbufp.contents[:(outbuflen.value)]
my_outs = outsp.contents[:(outslen.value)]
# free callee's allocations
if outbuflen.value:
run_in_thread(self.librados.rados_buffer_free, (outbufp.contents,))
if outslen.value:
run_in_thread(self.librados.rados_buffer_free, (outsp.contents,))
return (ret, my_outbuf, my_outs)
def osd_command(self, osdid, cmd, inbuf, timeout=0):
"""
osd_command(osdid, cmd, inbuf, outbuf, outbuflen, outs, outslen)
returns (int ret, string outbuf, string outs)
"""
import sys
self.require_state("connected")
outbufp = pointer(pointer(c_char()))
outbuflen = c_long()
outsp = pointer(pointer(c_char()))
outslen = c_long()
cmdarr = (c_char_p * len(cmd))(*cmd)
ret = run_in_thread(self.librados.rados_osd_command,
(self.cluster, osdid, cmdarr, len(cmd),
c_char_p(inbuf), len(inbuf),
outbufp, byref(outbuflen), outsp, byref(outslen)),
timeout)
# copy returned memory (ctypes makes a copy, not a reference)
my_outbuf = outbufp.contents[:(outbuflen.value)]
my_outs = outsp.contents[:(outslen.value)]
# free callee's allocations
if outbuflen.value:
run_in_thread(self.librados.rados_buffer_free, (outbufp.contents,))
if outslen.value:
run_in_thread(self.librados.rados_buffer_free, (outsp.contents,))
return (ret, my_outbuf, my_outs)
def pg_command(self, pgid, cmd, inbuf, timeout=0):
"""
pg_command(pgid, cmd, inbuf, outbuf, outbuflen, outs, outslen)
returns (int ret, string outbuf, string outs)
"""
import sys
self.require_state("connected")
outbufp = pointer(pointer(c_char()))
outbuflen = c_long()
outsp = pointer(pointer(c_char()))
outslen = c_long()
cmdarr = (c_char_p * len(cmd))(*cmd)
ret = run_in_thread(self.librados.rados_pg_command,
(self.cluster, c_char_p(pgid), cmdarr, len(cmd),
c_char_p(inbuf), len(inbuf),
outbufp, byref(outbuflen), outsp, byref(outslen)),
timeout)
# copy returned memory (ctypes makes a copy, not a reference)
my_outbuf = outbufp.contents[:(outbuflen.value)]
my_outs = outsp.contents[:(outslen.value)]
# free callee's allocations
if outbuflen.value:
run_in_thread(self.librados.rados_buffer_free, (outbufp.contents,))
if outslen.value:
run_in_thread(self.librados.rados_buffer_free, (outsp.contents,))
return (ret, my_outbuf, my_outs)
class ObjectIterator(object):
"""rados.Ioctx Object iterator"""
def __init__(self, ioctx):
self.ioctx = ioctx
self.ctx = c_void_p()
ret = run_in_thread(self.ioctx.librados.rados_objects_list_open,
(self.ioctx.io, byref(self.ctx)))
if ret < 0:
raise make_ex(ret, "error iterating over the objects in ioctx '%s'" \
% self.ioctx.name)
def __iter__(self):
return self
def next(self):
"""
Get the next object name and locator in the pool
:raises: StopIteration
:returns: next rados.Ioctx Object
"""
key = c_char_p()
locator = c_char_p()
ret = run_in_thread(self.ioctx.librados.rados_objects_list_next,
(self.ctx, byref(key), byref(locator)))
if ret < 0:
raise StopIteration()
return Object(self.ioctx, key.value, locator.value)
def __del__(self):
run_in_thread(self.ioctx.librados.rados_objects_list_close, (self.ctx,))
class XattrIterator(object):
"""Extended attribute iterator"""
def __init__(self, ioctx, it, oid):
self.ioctx = ioctx
self.it = it
self.oid = oid
def __iter__(self):
return self
def next(self):
"""
Get the next xattr on the object
:raises: StopIteration
:returns: pair - of name and value of the next Xattr
"""
name_ = c_char_p(0)
val_ = c_char_p(0)
len_ = c_int(0)
ret = run_in_thread(self.ioctx.librados.rados_getxattrs_next,
(self.it, byref(name_), byref(val_), byref(len_)))
if (ret != 0):
raise make_ex(ret, "error iterating over the extended attributes \
in '%s'" % self.oid)
if name_.value == None:
raise StopIteration()
name = ctypes.string_at(name_)
val = ctypes.string_at(val_, len_)
return (name, val)
def __del__(self):
run_in_thread(self.ioctx.librados.rados_getxattrs_end, (self.it,))
class SnapIterator(object):
"""Snapshot iterator"""
def __init__(self, ioctx):
self.ioctx = ioctx
# We don't know how big a buffer we need until we've called the
# function. So use the exponential doubling strategy.
num_snaps = 10
while True:
self.snaps = (ctypes.c_uint64 * num_snaps)()
ret = run_in_thread(self.ioctx.librados.rados_ioctx_snap_list,
(self.ioctx.io, self.snaps, c_int(num_snaps)))
if (ret >= 0):
self.max_snap = ret
break
elif (ret != -errno.ERANGE):
raise make_ex(ret, "error calling rados_snap_list for \
ioctx '%s'" % self.ioctx.name)
num_snaps = num_snaps * 2
self.cur_snap = 0
def __iter__(self):
return self
def next(self):
"""
Get the next Snapshot
:raises: :class:`Error`, StopIteration
:returns: Snap - next snapshot
"""
if (self.cur_snap >= self.max_snap):
raise StopIteration
snap_id = self.snaps[self.cur_snap]
name_len = 10
while True:
name = create_string_buffer(name_len)
ret = run_in_thread(self.ioctx.librados.rados_ioctx_snap_get_name,
(self.ioctx.io, c_uint64(snap_id), byref(name),
c_int(name_len)))
if (ret == 0):
name_len = ret
break
elif (ret != -errno.ERANGE):
raise make_ex(ret, "rados_snap_get_name error")
name_len = name_len * 2
snap = Snap(self.ioctx, name.value, snap_id)
self.cur_snap = self.cur_snap + 1
return snap
class Snap(object):
"""Snapshot object"""
def __init__(self, ioctx, name, snap_id):
self.ioctx = ioctx
self.name = name
self.snap_id = snap_id
def __str__(self):
return "rados.Snap(ioctx=%s,name=%s,snap_id=%d)" \
% (str(self.ioctx), self.name, self.snap_id)
def get_timestamp(self):
"""
Find when a snapshot in the current pool occurred
:raises: :class:`Error`
:returns: datetime - the data and time the snapshot was created
"""
snap_time = c_long(0)
ret = run_in_thread(self.ioctx.librados.rados_ioctx_snap_get_stamp,
(self.ioctx.io, self.snap_id, byref(snap_time)))
if (ret != 0):
raise make_ex(ret, "rados_ioctx_snap_get_stamp error")
return datetime.fromtimestamp(snap_time.value)
class Completion(object):
"""completion object"""
def __init__(self, ioctx, rados_comp, oncomplete, onsafe):
self.rados_comp = rados_comp
self.oncomplete = oncomplete
self.onsafe = onsafe
self.ioctx = ioctx
def wait_for_safe(self):
"""
Is an asynchronous operation safe?
This does not imply that the safe callback has finished.
:returns: whether the operation is safe
"""
return run_in_thread(self.ioctx.librados.rados_aio_is_safe,
(self.rados_comp,))
def wait_for_complete(self):
"""
Has an asynchronous operation completed?
This does not imply that the safe callback has finished.
:returns: whether the operation is completed
"""
return run_in_thread(self.ioctx.librados.rados_aio_is_complete,
(self.rados_comp,))
def get_return_value(self):
"""
Get the return value of an asychronous operation
The return value is set when the operation is complete or safe,
whichever comes first.
:returns: int - return value of the operation
"""
return run_in_thread(self.ioctx.librados.rados_aio_get_return_value,
(self.rados_comp,))
def __del__(self):
"""
Release a completion
Call this when you no longer need the completion. It may not be
freed immediately if the operation is not acked and committed.
"""
run_in_thread(self.ioctx.librados.rados_aio_release,
(self.rados_comp,))
class Ioctx(object):
"""rados.Ioctx object"""
def __init__(self, name, librados, io):
self.name = name
self.librados = librados
self.io = io
self.state = "open"
self.locator_key = ""
self.safe_cbs = {}
self.complete_cbs = {}
RADOS_CB = CFUNCTYPE(c_int, c_void_p, c_void_p)
self.__aio_safe_cb_c = RADOS_CB(self.__aio_safe_cb)
self.__aio_complete_cb_c = RADOS_CB(self.__aio_complete_cb)
self.lock = threading.Lock()
def __enter__(self):
return self
def __exit__(self, type_, value, traceback):
self.close()
return False
def __del__(self):
self.close()
def __aio_safe_cb(self, completion, _):
"""
Callback to onsafe() for asynchronous operations
"""
cb = None
with self.lock:
cb = self.safe_cbs[completion]
del self.safe_cbs[completion]
cb.onsafe(cb)
return 0
def __aio_complete_cb(self, completion, _):
"""
Callback to oncomplete() for asynchronous operations
"""
cb = None
with self.lock:
cb = self.complete_cbs[completion]
del self.complete_cbs[completion]
cb.oncomplete(cb)
return 0
def __get_completion(self, oncomplete, onsafe):
"""
Constructs a completion to use with asynchronous operations
:param oncomplete: what to do when the write is safe and complete in memory
on all replicas
:type oncomplete: completion
:param onsafe: what to do when the write is safe and complete on storage
on all replicas
:type onsafe: completion
:raises: :class:`Error`
:returns: completion object
"""
completion = c_void_p(0)
complete_cb = None
safe_cb = None
if oncomplete:
complete_cb = self.__aio_complete_cb_c
if onsafe:
safe_cb = self.__aio_safe_cb_c
ret = run_in_thread(self.librados.rados_aio_create_completion,
(c_void_p(0), complete_cb, safe_cb,
byref(completion)))
if ret < 0:
raise make_ex(ret, "error getting a completion")
with self.lock:
completion_obj = Completion(self, completion, oncomplete, onsafe)
if oncomplete:
self.complete_cbs[completion.value] = completion_obj
if onsafe:
self.safe_cbs[completion.value] = completion_obj
return completion_obj
def aio_write(self, object_name, to_write, offset=0,
oncomplete=None, onsafe=None):
"""
Write data to an object asynchronously
Queues the write and returns.
:param object_name: name of the object
:type object_name: str
:param to_write: data to write
:type to_write: str
:param offset: byte offset in the object to begin writing at
:type offset: int
:param oncomplete: what to do when the write is safe and complete in memory
on all replicas
:type oncomplete: completion
:param onsafe: what to do when the write is safe and complete on storage
on all replicas
:type onsafe: completion
:raises: :class:`Error`
:returns: completion object
"""
completion = self.__get_completion(oncomplete, onsafe)
ret = run_in_thread(self.librados.rados_aio_write,
(self.io, c_char_p(object_name),
completion.rados_comp, c_char_p(to_write),
c_size_t(len(to_write)), c_uint64(offset)))
if ret < 0:
raise make_ex(ret, "error writing object %s" % object_name)
return completion
def aio_write_full(self, object_name, to_write,
oncomplete=None, onsafe=None):
"""
Asychronously write an entire object
The object is filled with the provided data. If the object exists,
it is atomically truncated and then written.
Queues the write and returns.
:param object_name: name of the object
:type object_name: str
:param to_write: data to write
:type to_write: str
:param oncomplete: what to do when the write is safe and complete in memory
on all replicas
:type oncomplete: completion
:param onsafe: what to do when the write is safe and complete on storage
on all replicas
:type onsafe: completion
:raises: :class:`Error`
:returns: completion object
"""
completion = self.__get_completion(oncomplete, onsafe)
ret = run_in_thread(self.librados.rados_aio_write_full,
(self.io, c_char_p(object_name),
completion.rados_comp, c_char_p(to_write),
c_size_t(len(to_write))))
if ret < 0:
raise make_ex(ret, "error writing object %s" % object_name)
return completion
def aio_append(self, object_name, to_append, oncomplete=None, onsafe=None):
"""
Asychronously append data to an object
Queues the write and returns.
:param object_name: name of the object
:type object_name: str
:param to_append: data to append
:type to_append: str
:param offset: byte offset in the object to begin writing at
:type offset: int
:param oncomplete: what to do when the write is safe and complete in memory
on all replicas
:type oncomplete: completion
:param onsafe: what to do when the write is safe and complete on storage
on all replicas
:type onsafe: completion
:raises: :class:`Error`
:returns: completion object
"""
completion = self.__get_completion(oncomplete, onsafe)
ret = run_in_thread(self.librados.rados_aio_append,
(self.io, c_char_p(object_name),
completion.rados_comp, c_char_p(to_append),
c_size_t(len(to_append))))
if ret < 0:
raise make_ex(ret, "error appending to object %s" % object_name)
return completion
def aio_flush(self):
"""
Block until all pending writes in an io context are safe
:raises: :class:`Error`
"""
ret = run_in_thread(self.librados.rados_aio_flush, (self.io,))
if ret < 0:
raise make_ex(ret, "error flushing")
def aio_read(self, object_name, length, offset, oncomplete):
"""
Asychronously read data from an object
oncomplete will be called with the returned read value as
well as the completion:
oncomplete(completion, data_read)
:param object_name: name of the object to read from
:type object_name: str
:param length: the number of bytes to read
:type length: int
:param offset: byte offset in the object to begin reading from
:type offset: int
:param oncomplete: what to do when the read is complete
:type oncomplete: completion
:raises: :class:`Error`
:returns: completion object
"""
buf = create_string_buffer(length)
def oncomplete_(completion):
return oncomplete(completion, buf.value)
completion = self.__get_completion(oncomplete_, None)
ret = run_in_thread(self.librados.rados_aio_read,
(self.io, c_char_p(object_name),
completion.rados_comp, buf, c_size_t(length),
c_uint64(offset)))
if ret < 0:
raise make_ex(ret, "error reading %s" % object_name)
return completion
def aio_remove(self, object_name, oncomplete=None, onsafe=None):
"""
Asychronously remove an object
:param object_name: name of the object to remove
:type object_name: str
:param oncomplete: what to do when the remove is safe and complete in memory
on all replicas
:type oncomplete: completion
:param onsafe: what to do when the remove is safe and complete on storage
on all replicas
:type onsafe: completion
:raises: :class:`Error`
:returns: completion object
"""
completion = self.__get_completion(oncomplete, onsafe)
ret = run_in_thread(self.librados.rados_aio_remove,
(self.io, c_char_p(object_name),
completion.rados_comp))
if ret < 0:
raise make_ex(ret, "error removing %s" % object_name)
return completion
def require_ioctx_open(self):
"""
Checks if the rados.Ioctx object state is 'open'
:raises: IoctxStateError
"""
if self.state != "open":
raise IoctxStateError("The pool is %s" % self.state)
def change_auid(self, auid):
"""
Attempt to change an io context's associated auid "owner."
Requires that you have write permission on both the current and new
auid.
:raises: :class:`Error`
"""
self.require_ioctx_open()
ret = run_in_thread(self.librados.rados_ioctx_pool_set_auid,
(self.io, ctypes.c_uint64(auid)))
if ret < 0:
raise make_ex(ret, "error changing auid of '%s' to %d" %\
(self.name, auid))
def set_locator_key(self, loc_key):
"""
Set the key for mapping objects to pgs within an io context.
The key is used instead of the object name to determine which
placement groups an object is put in. This affects all subsequent
operations of the io context - until a different locator key is
set, all objects in this io context will be placed in the same pg.
:param loc_key: the key to use as the object locator, or NULL to discard
any previously set key
:type loc_key: str
:raises: :class:`TypeError`
"""
self.require_ioctx_open()
if not isinstance(loc_key, str):
raise TypeError('loc_key must be a string')
run_in_thread(self.librados.rados_ioctx_locator_set_key,
(self.io, c_char_p(loc_key)))
self.locator_key = loc_key
def get_locator_key(self):
"""
Get the locator_key of context
:returns: locator_key
"""
return self.locator_key
def close(self):
"""
Close a rados.Ioctx object.
This just tells librados that you no longer need to use the io context.
It may not be freed immediately if there are pending asynchronous
requests on it, but you should not use an io context again after
calling this function on it.
"""
if self.state == "open":
self.require_ioctx_open()
run_in_thread(self.librados.rados_ioctx_destroy, (self.io,))
self.state = "closed"
def write(self, key, data, offset=0):
"""
Write data to an object synchronously
:param key: name of the object
:type key: str
:param data: data to write
:type data: str
:param offset: byte offset in the object to begin writing at
:type offset: int
:raises: :class:`TypeError`
:raises: :class:`IncompleteWriteError`
:raises: :class:`LogicError`
:returns: int - number of bytes written
"""
self.require_ioctx_open()
if not isinstance(data, str):
raise TypeError('data must be a string')
length = len(data)
ret = run_in_thread(self.librados.rados_write,
(self.io, c_char_p(key), c_char_p(data),
c_size_t(length), c_uint64(offset)))
if ret == length:
return ret
elif ret < 0:
raise make_ex(ret, "Ioctx.write(%s): failed to write %s" % \
(self.name, key))
elif ret < length:
raise IncompleteWriteError("Wrote only %d out of %d bytes" % \
(ret, length))
else:
raise LogicError("Ioctx.write(%s): rados_write \
returned %d, but %d was the maximum number of bytes it could have \
written." % (self.name, ret, length))
def write_full(self, key, data):
"""
Write an entire object synchronously.
The object is filled with the provided data. If the object exists,
it is atomically truncated and then written.
:param key: name of the object
:type key: str
:param data: data to write
:type data: str
:raises: :class:`TypeError`
:raises: :class:`Error`
:returns: int - 0 on success
"""
self.require_ioctx_open()
if not isinstance(key, str):
raise TypeError('key must be a string')
if not isinstance(data, str):
raise TypeError('data must be a string')
length = len(data)
ret = run_in_thread(self.librados.rados_write_full,
(self.io, c_char_p(key), c_char_p(data),
c_size_t(length)))
if ret == 0:
return ret
else:
raise make_ex(ret, "Ioctx.write(%s): failed to write_full %s" % \
(self.name, key))
def read(self, key, length=8192, offset=0):
"""
Read data from an object synchronously
:param key: name of the object
:type key: str
:param length: the number of bytes to read (default=8192)
:type length: int
:param offset: byte offset in the object to begin reading at
:type offset: int
:raises: :class:`TypeError`
:raises: :class:`Error`
:returns: str - data read from object
"""
self.require_ioctx_open()
if not isinstance(key, str):
raise TypeError('key must be a string')
ret_buf = create_string_buffer(length)
ret = run_in_thread(self.librados.rados_read,
(self.io, c_char_p(key), ret_buf, c_size_t(length),
c_uint64(offset)))
if ret < 0:
raise make_ex(ret, "Ioctx.read(%s): failed to read %s" % (self.name, key))
return ctypes.string_at(ret_buf, ret)
def get_stats(self):
"""
Get pool usage statistics
:returns: dict - contains the following keys:
- ``num_bytes`` (int) - size of pool in bytes
- ``num_kb`` (int) - size of pool in kbytes
- ``num_objects`` (int) - number of objects in the pool
- ``num_object_clones`` (int) - number of object clones
- ``num_object_copies`` (int) - number of object copies
- ``num_objects_missing_on_primary`` (int) - number of objets
missing on primary
- ``num_objects_unfound`` (int) - number of unfound objects
- ``num_objects_degraded`` (int) - number of degraded objects
- ``num_rd`` (int) - bytes read
- ``num_rd_kb`` (int) - kbytes read
- ``num_wr`` (int) - bytes written
- ``num_wr_kb`` (int) - kbytes written
"""
self.require_ioctx_open()
stats = rados_pool_stat_t()
ret = run_in_thread(self.librados.rados_ioctx_pool_stat,
(self.io, byref(stats)))
if ret < 0:
raise make_ex(ret, "Ioctx.get_stats(%s): get_stats failed" % self.name)
return {'num_bytes': stats.num_bytes,
'num_kb': stats.num_kb,
'num_objects': stats.num_objects,
'num_object_clones': stats.num_object_clones,
'num_object_copies': stats.num_object_copies,
"num_objects_missing_on_primary": stats.num_objects_missing_on_primary,
"num_objects_unfound": stats.num_objects_unfound,
"num_objects_degraded": stats.num_objects_degraded,
"num_rd": stats.num_rd,
"num_rd_kb": stats.num_rd_kb,
"num_wr": stats.num_wr,
"num_wr_kb": stats.num_wr_kb }
def remove_object(self, key):
"""
Delete an object
This does not delete any snapshots of the object.
:param key: the name of the object to delete
:type key: str
:raises: :class:`TypeError`
:raises: :class:`Error`
:returns: bool - True on success
"""
self.require_ioctx_open()
if not isinstance(key, str):
raise TypeError('key must be a string')
ret = run_in_thread(self.librados.rados_remove,
(self.io, c_char_p(key)))
if ret < 0:
raise make_ex(ret, "Failed to remove '%s'" % key)
return True
def trunc(self, key, size):
"""
Resize an object
If this enlarges the object, the new area is logically filled with
zeroes. If this shrinks the object, the excess data is removed.
:param key: the name of the object to resize
:type key: str
:param size: the new size of the object in bytes
:type size: int
:raises: :class:`TypeError`
:raises: :class:`Error`
:returns: int - 0 on success, otherwise raises error
"""
self.require_ioctx_open()
if not isinstance(key, str):
raise TypeError('key must be a string')
ret = run_in_thread(self.librados.rados_trunc,
(self.io, c_char_p(key), c_uint64(size)))
if ret < 0:
raise make_ex(ret, "Ioctx.trunc(%s): failed to truncate %s" % (self.name, key))
return ret
def stat(self, key):
"""
Get object stats (size/mtime)
:param key: the name of the object to get stats from
:type key: str
:raises: :class:`TypeError`
:raises: :class:`Error`
:returns: (size,timestamp)
"""
self.require_ioctx_open()
if not isinstance(key, str):
raise TypeError('key must be a string')
psize = c_uint64()
pmtime = c_uint64()
ret = run_in_thread(self.librados.rados_stat,
(self.io, c_char_p(key), pointer(psize),
pointer(pmtime)))
if ret < 0:
raise make_ex(ret, "Failed to stat %r" % key)
return psize.value, time.localtime(pmtime.value)
def get_xattr(self, key, xattr_name):
"""
Get the value of an extended attribute on an object.
:param key: the name of the object to get xattr from
:type key: str
:param xattr_name: which extended attribute to read
:type xattr_name: str
:raises: :class:`TypeError`
:raises: :class:`Error`
:returns: str - value of the xattr
"""
self.require_ioctx_open()
if not isinstance(xattr_name, str):
raise TypeError('xattr_name must be a string')
ret_length = 4096
while ret_length < 4096 * 1024 * 1024:
ret_buf = create_string_buffer(ret_length)
ret = run_in_thread(self.librados.rados_getxattr,
(self.io, c_char_p(key), c_char_p(xattr_name),
ret_buf, c_size_t(ret_length)))
if (ret == -errno.ERANGE):
ret_length *= 2
elif ret < 0:
raise make_ex(ret, "Failed to get xattr %r" % xattr_name)
else:
break
return ctypes.string_at(ret_buf, ret)
def get_xattrs(self, oid):
"""
Start iterating over xattrs on an object.
:param oid: the name of the object to get xattrs from
:type key: str
:raises: :class:`TypeError`
:raises: :class:`Error`
:returns: XattrIterator
"""
self.require_ioctx_open()
if not isinstance(oid, str):
raise TypeError('oid must be a string')
it = c_void_p(0)
ret = run_in_thread(self.librados.rados_getxattrs,
(self.io, oid, byref(it)))
if ret != 0:
raise make_ex(ret, "Failed to get rados xattrs for object %r" % oid)
return XattrIterator(self, it, oid)
def set_xattr(self, key, xattr_name, xattr_value):
"""
Set an extended attribute on an object.
:param key: the name of the object to set xattr to
:type key: str
:param xattr_name: which extended attribute to set
:type xattr_name: str
:param xattr_value: the value of the extended attribute
:type xattr_value: str
:raises: :class:`TypeError`
:raises: :class:`Error`
:returns: bool - True on success, otherwise raise an error
"""
self.require_ioctx_open()
if not isinstance(key, str):
raise TypeError('key must be a string')
if not isinstance(xattr_name, str):
raise TypeError('xattr_name must be a string')
if not isinstance(xattr_value, str):
raise TypeError('xattr_value must be a string')
ret = run_in_thread(self.librados.rados_setxattr,
(self.io, c_char_p(key), c_char_p(xattr_name),
c_char_p(xattr_value), c_size_t(len(xattr_value))))
if ret < 0:
raise make_ex(ret, "Failed to set xattr %r" % xattr_name)
return True
def rm_xattr(self, key, xattr_name):
"""
Removes an extended attribute on from an object.
:param key: the name of the object to remove xattr from
:type key: str
:param xattr_name: which extended attribute to remove
:type xattr_name: str
:raises: :class:`TypeError`
:raises: :class:`Error`
:returns: bool - True on success, otherwise raise an error
"""
self.require_ioctx_open()
if not isinstance(key, str):
raise TypeError('key must be a string')
if not isinstance(xattr_name, str):
raise TypeError('xattr_name must be a string')
ret = run_in_thread(self.librados.rados_rmxattr,
(self.io, c_char_p(key), c_char_p(xattr_name)))
if ret < 0:
raise make_ex(ret, "Failed to delete key %r xattr %r" %
(key, xattr_name))
return True
def list_objects(self):
"""
Get ObjectIterator on rados.Ioctx object.
:returns: ObjectIterator
"""
self.require_ioctx_open()
return ObjectIterator(self)
def list_snaps(self):
"""
Get SnapIterator on rados.Ioctx object.
:returns: SnapIterator
"""
self.require_ioctx_open()
return SnapIterator(self)
def create_snap(self, snap_name):
"""
Create a pool-wide snapshot
:param snap_name: the name of the snapshot
:type snap_name: str
:raises: :class:`TypeError`
:raises: :class:`Error`
"""
self.require_ioctx_open()
if not isinstance(snap_name, str):
raise TypeError('snap_name must be a string')
ret = run_in_thread(self.librados.rados_ioctx_snap_create,
(self.io, c_char_p(snap_name)))
if (ret != 0):
raise make_ex(ret, "Failed to create snap %s" % snap_name)
def remove_snap(self, snap_name):
"""
Removes a pool-wide snapshot
:param snap_name: the name of the snapshot
:type snap_name: str
:raises: :class:`TypeError`
:raises: :class:`Error`
"""
self.require_ioctx_open()
if not isinstance(snap_name, str):
raise TypeError('snap_name must be a string')
ret = run_in_thread(self.librados.rados_ioctx_snap_remove,
(self.io, c_char_p(snap_name)))
if (ret != 0):
raise make_ex(ret, "Failed to remove snap %s" % snap_name)
def lookup_snap(self, snap_name):
"""
Get the id of a pool snapshot
:param snap_name: the name of the snapshot to lookop
:type snap_name: str
:raises: :class:`TypeError`
:raises: :class:`Error`
:returns: Snap - on success
"""
self.require_ioctx_open()
if not isinstance(snap_name, str):
raise TypeError('snap_name must be a string')
snap_id = c_uint64()
ret = run_in_thread(self.librados.rados_ioctx_snap_lookup,
(self.io, c_char_p(snap_name), byref(snap_id)))
if (ret != 0):
raise make_ex(ret, "Failed to lookup snap %s" % snap_name)
return Snap(self, snap_name, snap_id)
def get_last_version(self):
"""
Return the version of the last object read or written to.
This exposes the internal version number of the last object read or
written via this io context
:returns: version of the last object used
"""
self.require_ioctx_open()
return run_in_thread(self.librados.rados_get_last_version, (self.io,))
def set_object_locator(func):
def retfunc(self, *args, **kwargs):
if self.locator_key is not None:
old_locator = self.ioctx.get_locator_key()
self.ioctx.set_locator_key(self.locator_key)
retval = func(self, *args, **kwargs)
self.ioctx.set_locator_key(old_locator)
return retval
else:
return func(self, *args, **kwargs)
return retfunc
class Object(object):
"""Rados object wrapper, makes the object look like a file"""
def __init__(self, ioctx, key, locator_key=None):
self.key = key
self.ioctx = ioctx
self.offset = 0
self.state = "exists"
self.locator_key = locator_key
def __str__(self):
return "rados.Object(ioctx=%s,key=%s)" % (str(self.ioctx), self.key)
def require_object_exists(self):
if self.state != "exists":
raise ObjectStateError("The object is %s" % self.state)
@set_object_locator
def read(self, length = 1024*1024):
self.require_object_exists()
ret = self.ioctx.read(self.key, length, self.offset)
self.offset += len(ret)
return ret
@set_object_locator
def write(self, string_to_write):
self.require_object_exists()
ret = self.ioctx.write(self.key, string_to_write, self.offset)
self.offset += ret
return ret
@set_object_locator
def remove(self):
self.require_object_exists()
self.ioctx.remove_object(self.key)
self.state = "removed"
@set_object_locator
def stat(self):
self.require_object_exists()
return self.ioctx.stat(self.key)
def seek(self, position):
self.require_object_exists()
self.offset = position
@set_object_locator
def get_xattr(self, xattr_name):
self.require_object_exists()
return self.ioctx.get_xattr(self.key, xattr_name)
@set_object_locator
def get_xattrs(self):
self.require_object_exists()
return self.ioctx.get_xattrs(self.key)
@set_object_locator
def set_xattr(self, xattr_name, xattr_value):
self.require_object_exists()
return self.ioctx.set_xattr(self.key, xattr_name, xattr_value)
@set_object_locator
def rm_xattr(self, xattr_name):
self.require_object_exists()
return self.ioctx.rm_xattr(self.key, xattr_name)
MONITOR_LEVELS = [
"debug",
"info",
"warn", "warning",
"err", "error",
"sec",
]
class MonitorLog(object):
"""
For watching cluster log messages. Instantiate an object and keep
it around while callback is periodically called. Construct with
'level' to monitor 'level' messages (one of MONITOR_LEVELS).
arg will be passed to the callback.
callback will be called with:
arg (given to __init__)
line (the full line, including timestamp, who, level, msg)
who (which entity issued the log message)
timestamp_sec (sec of a struct timespec)
timestamp_nsec (sec of a struct timespec)
seq (sequence number)
level (string representing the level of the log message)
msg (the message itself)
callback's return value is ignored
"""
def monitor_log_callback(self, arg, line, who, sec, nsec, seq, level, msg):
"""
Local callback wrapper, in case we decide to do something
"""
self.callback(arg, line, who, sec, nsec, seq, level, msg)
return 0
def __init__(self, cluster, level, callback, arg):
if level not in MONITOR_LEVELS:
raise LogicError("invalid monitor level " + level)
if not callable(callback):
raise LogicError("callback must be a callable function")
self.level = level
self.callback = callback
self.arg = arg
callback_factory = CFUNCTYPE(c_int, # return type (really void)
c_void_p, # arg
c_char_p, # line
c_char_p, # who
c_uint64, # timestamp_sec
c_uint64, # timestamp_nsec
c_ulong, # seq
c_char_p, # level
c_char_p) # msg
self.internal_callback = callback_factory(self.monitor_log_callback)
r = run_in_thread(cluster.librados.rados_monitor_log,
(cluster.cluster, level, self.internal_callback, arg))
if r:
raise make_ex(r, 'error calling rados_monitor_log')
|