/usr/share/pyshared/pywbem/cim_provider2.py is in python-pywbem 0.7.0-4.
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 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 | #
# (C) Copyright 2003-2007 Hewlett-Packard Development Company, L.P.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation; either version 2 of the
# License.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
# Author: Bart Whiteley
# Jon Carey
####
"""Python CIM Providers (aka "nirvana")
This module is an abstraction and utility layer between a CIMOM and
Python providers. The CIMOM uses this module to load Python providers,
and route requests to those providers.
Python Provider Modules
Python Providers are implemented as Python modules. By convention
these modules are installed into /usr/lib/pycim. However, they can
be anywhere. These modules are loaded on demand using load_module()
from the imp module. The CIMOM's pycim interface stores the timestamp
of the provider modules. If the modules change, the CIMOM reloads the
modules. This is very useful while developing providers, since the
latest code will always be loaded and used.
A Python Provider Module will contain functions, attributes, and
instances that will be accessed and manipulated by this module.
Providers are often classified in the following catagories:
Instance -- Instrument the retrieval, creation, modification,
and deletion of CIM instances.
Association -- Instrument CIM associations (CIM classes with the
Association qualifier).
Method -- Instrument methods as defined on CIM instances or CIM
classes.
Indication -- Generates indications based on indication
subscriptions.
Indication Consumer -- "Consumes" (or "Handles") an indication,
possibly delivering it through some other means, such as email.
Polled -- A polled provider is allowed to run periodically (by
calling its poll function). This allows a provider to do some
periodic work, without the need to create its own thread.
An Instance, Association, and/or Method provider is created by defining
one or more subclasses of CIMProvider2 within the provider module, and
registering instances of the subclass(es) with CIM class names by way
of the get_providers function (described below). Refer to
the documentation for CIMProvider2 in this module.
Indication, Indication Consumer, and Polled providers are defined by
implementing some functions within the provider module.
Provider module functions:
init(env):
This module function is optional. It is called immediately
after the provider module is imported.
Arguments:
env -- Provider Environment (pycimmb.ProviderEnvironment)
get_providers(env):
Return a dict that maps CIM class names to instances of
CIMProvider2 subclasses. Note that multiple classes can be
instrumented by the same instance of a CIMProvider2 subclass.
The CIM class names are case-insensitive, since this dict is
converted to a NocaseDict.
Arguments:
env -- Provider Environment (pycimmb.ProviderEnvironment)
For example, a Python Provider Module may contain the following:
class Py_FooBarProvider(CIMProvider2):
...
def get_providers(env):
_fbp = Py_FooBarProvider()
return {'Py_Foo':_fbp, 'Py_Bar':_fbp}
can_unload(env):
Return True if the provider can be unloaded.
The CIMOM may try to unload a provider after a period of inactivity.
Before unloading a provider, the CIMOM asks the provider if it can
be unloaded.
Arguments:
env -- Provider Environment (pycimmb.ProviderEnvironment)
shutdown(env):
Perform any cleanup tasks prior to being unloaded.
The provider will shortly be unloaded, and is given an opportunity
to perform any needed cleanup. The provider may be unloaded after
a period of inactivity (see the documentation for can_unload), or
because the CIMOM is shutting down.
Arguments:
env -- Provider Environment (pycimmb.ProviderEnvironment)
handle_indication(env, ns, handler_instance, indication_instance):
Process an indication.
Arguments:
env -- Provider Environment (pycimmb.ProviderEnvironment)
ns -- The namespace where the event occurred
handler_instance --
indication_instance -- The indication
authorize_filter (env, filter, ns, classes,
owner):
Allow or disallow an indication subscription request.
Arguments:
env -- Provider Environment (pycimmb.ProviderEnvironment)
filter -- The WQL select statement
namespace -- The namepace where the indication is registered for
classes -- The classpath of the indication registered for
owner -- The name of the principal (cimom user)
activate_filter (env, filter, ns, classes,
first_activation):
Activate an indication subscription.
Arguments:
env -- Provider Environment (pycimmb.ProviderEnvironment)
filter -- The WQL select statement
namespace -- The namepace where the indication is registered for
classes -- The classpath of the indication registered for
first_activation -- boolean - whether first activation
deactivate_filter(env, filter, ns, classes,
last_activation):
Deactivate an indication subscription.
Arguments:
env -- Provider Environment (pycimmb.ProviderEnvironment)
filter -- The WQL select statement
ns -- The namepace where the indication is registered for
classes -- The classpath of the indication registered for
last_activation -- boolean - whether last activation
enable_indications(env):
Enable indications.
Arguments:
env -- Provider Environment (pycimmb.ProviderEnvironment)
disable_indications(env):
Disable indications.
Arguments:
env -- Provider Environment (pycimmb.ProviderEnvironment)
Provider Environment
A pycimmb.ProviderEnvironment is passed to many functions. This is
a handle back into the CIMOM. You can use it for logging and for
making "up-calls" to the CIMOM. For example:
logger = env.get_logger()
logger.log_debug('Debug Info')
ch = env.get_cimom_handle()
other_inst = ch.GetInstance(inst_path, LocalOnly=False,
IncludeQualifiers=False,
IncludeClassOrigin=False)
The API of the pycimmb.CIMOMHandle resembles that of
pywbem.WBEMConnection.
For more information on the ProviderEnvironments, and other features
provided by pycimmb, refer to the pycimmb documentation.
CodeGen
The codegen function can be used to generate provider stub code for a
given CIM class. This is a quick way to get started writing a provider.
"""
import sys
from os.path import dirname
import pywbem
import types
import sys # for sys.modules
import os
import imp
import threading
g_mod_lock = threading.RLock()
__all__ = ['CIMProvider2', 'codegen']
def _paths_equal(lhs, rhs):
"""If one object path doesn't inlcude a host, don't include the hosts
in the comparison
"""
if lhs is rhs:
return True
if lhs.host is not None and rhs.host is not None and lhs.host != rhs.host:
return False
# need to make sure this stays in sync with CIMInstanceName.__cmp__()
return not (pywbem.cmpname(rhs.classname, lhs.classname) or
cmp(rhs.keybindings, lhs.keybindings) or
pywbem.cmpname(rhs.namespace, lhs.namespace))
class CIMProvider2(object):
"""Base class for CIM Providers.
A derived class might normally override the following:
- enum_instances
- get_instance
- set_instance
- delete_instance
- references
If the provider is a "read-only" instance provider, set_instance and
delete_instance need not be overridden.
Only association providers need to override references.
A method provider should implement a method of the form:
def cim_method_<method_name>(self, env, object_name, method,
param_<input_param_1>,
param_<input_param_2>,
...):
Where <method_name> is the name of the method from the CIM schema.
<method_name> needs to be all lowercase, regardless of the case of
the method name in the CIM schema (CIM method names are case
insensitive).
Keyword arguments:
env -- Provider Environment (pycimmb.ProviderEnvironment)
object_name -- A pywbem.CIMInstanceName or pywbem.CIMClassname
specifying the object on which the method is to be invoked.
method -- A pywbem.CIMMethod, representing the method to execute.
param_<param_name> -- Corresponds to the input parameter <param_name>
from the CIM schema. <param_name> needs to be all lowercase,
regardless of the case of the parameter name in the CIM schema
(CIM parameter names are case insensitive).
The method returns a two-tuple containing the return value of the
method, and a dictionary containing the output parameters.
Example:
def cim_method_requeststatechange(self, env, object_name, method,
param_requestedstate,
param_timeoutperiod):
# do stuff.
out_params = {'job': pywbem.CIMInstanceName(...)}
rval = pywbem.Uint32(0)
return (rval, out_params)
The methods prefixed with "MI_" correspond to the WBEM operations
from http://www.dmtf.org/standards/published_documents/DSP200.html
The default implementations of these methods call the methods
described above. These will not normally be overridden or extended
by a subclass.
"""
def get_instance (self, env, model):
"""Return an instance.
Keyword arguments:
env -- Provider Environment (pycimmb.ProviderEnvironment)
model -- A template of the pywbem.CIMInstance to be returned. The
key properties are set on this instance to correspond to the
instanceName that was requested. The properties of the model
are already filtered according to the PropertyList from the
request. Only properties present in the model need to be
given values. If you prefer, you can set all of the
values, and the instance will be filtered for you.
Possible Errors:
CIM_ERR_ACCESS_DENIED
CIM_ERR_INVALID_PARAMETER (including missing, duplicate, unrecognized
or otherwise incorrect parameters)
CIM_ERR_NOT_FOUND (the CIM Class does exist, but the requested CIM
Instance does not exist in the specified namespace)
CIM_ERR_FAILED (some other unspecified error occurred)
"""
return None
def enum_instances(self, env, model, keys_only):
"""Enumerate instances.
The WBEM operations EnumerateInstances and EnumerateInstanceNames
are both mapped to this method.
This method is a python generator
Keyword arguments:
env -- Provider Environment (pycimmb.ProviderEnvironment)
model -- A template of the pywbem.CIMInstances to be generated.
The properties of the model are already filtered according to
the PropertyList from the request. Only properties present in
the model need to be given values. If you prefer, you can
always set all of the values, and the instance will be filtered
for you.
keys_only -- A boolean. True if only the key properties should be
set on the generated instances.
Possible Errors:
CIM_ERR_FAILED (some other unspecified error occurred)
"""
pass
def set_instance(self, env, instance, modify_existing):
"""Return a newly created or modified instance.
Keyword arguments:
env -- Provider Environment (pycimmb.ProviderEnvironment)
instance -- The new pywbem.CIMInstance. If modifying an existing
instance, the properties on this instance have been filtered by
the PropertyList from the request.
modify_existing -- True if ModifyInstance, False if CreateInstance
Return the new instance. The keys must be set on the new instance.
Possible Errors:
CIM_ERR_ACCESS_DENIED
CIM_ERR_NOT_SUPPORTED
CIM_ERR_INVALID_PARAMETER (including missing, duplicate, unrecognized
or otherwise incorrect parameters)
CIM_ERR_ALREADY_EXISTS (the CIM Instance already exists -- only
valid if modify_existing is False, indicating that the operation
was CreateInstance)
CIM_ERR_NOT_FOUND (the CIM Instance does not exist -- only valid
if modify_existing is True, indicating that the operation
was ModifyInstance)
CIM_ERR_FAILED (some other unspecified error occurred)
"""
raise pywbem.CIMError(pywbem.CIM_ERR_NOT_SUPPORTED, "")
def delete_instance(self, env, instance_name):
"""Delete an instance.
Keyword arguments:
env -- Provider Environment (pycimmb.ProviderEnvironment)
instance_name -- A pywbem.CIMInstanceName specifying the instance
to delete.
Possible Errors:
CIM_ERR_ACCESS_DENIED
CIM_ERR_NOT_SUPPORTED
CIM_ERR_INVALID_NAMESPACE
CIM_ERR_INVALID_PARAMETER (including missing, duplicate, unrecognized
or otherwise incorrect parameters)
CIM_ERR_INVALID_CLASS (the CIM Class does not exist in the specified
namespace)
CIM_ERR_NOT_FOUND (the CIM Class does exist, but the requested CIM
Instance does not exist in the specified namespace)
CIM_ERR_FAILED (some other unspecified error occurred)
"""
raise pywbem.CIMError(pywbem.CIM_ERR_NOT_SUPPORTED, "")
def references(self, env, object_name, model,
result_class_name, role, result_role, keys_only):
"""Instrument Associations.
All four association-related operations (Associators, AssociatorNames,
References, ReferenceNames) are mapped to this method.
This method is a python generator
Keyword arguments:
env -- Provider Environment (pycimmb.ProviderEnvironment)
object_name -- A pywbem.CIMInstanceName that defines the source
CIM Object whose associated Objects are to be returned.
model -- A template pywbem.CIMInstance to serve as a model
of the objects to be returned. Only properties present on this
model need to be set.
result_class_name -- If not empty, this string acts as a filter on
the returned set of Instances by mandating that each returned
Instances MUST represent an association between object_name
and an Instance of a Class whose name matches this parameter
or a subclass.
role -- If not empty, MUST be a valid Property name. It acts as a
filter on the returned set of Instances by mandating that each
returned Instance MUST refer to object_name via a Property
whose name matches the value of this parameter.
result_role -- If not empty, MUST be a valid Property name. It acts
as a filter on the returned set of Instances by mandating that
each returned Instance MUST represent associations of
object_name to other Instances, where the other Instances play
the specified result_role in the association (i.e. the
name of the Property in the Association Class that refers to
the Object related to object_name MUST match the value of this
parameter).
keys_only -- A boolean. True if only the key properties should be
set on the generated instances.
The following diagram may be helpful in understanding the role,
result_role, and result_class_name parameters.
+------------------------+ +-------------------+
| object_name.classname | | result_class_name |
| ~~~~~~~~~~~~~~~~~~~~~ | | ~~~~~~~~~~~~~~~~~ |
+------------------------+ +-------------------+
| +-----------------------------------+ |
| | [Association] model.classname | |
| object_name | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | |
+--------------+ object_name.classname REF role | |
(CIMInstanceName) | result_class_name REF result_role +------+
| |(CIMInstanceName)
+-----------------------------------+
Possible Errors:
CIM_ERR_ACCESS_DENIED
CIM_ERR_NOT_SUPPORTED
CIM_ERR_INVALID_NAMESPACE
CIM_ERR_INVALID_PARAMETER (including missing, duplicate, unrecognized
or otherwise incorrect parameters)
CIM_ERR_FAILED (some other unspecified error occurred)
"""
# Don't change this return value. If affects the behavior
# of the MI_* methods.
return None
def simple_refs(self, env, object_name, model,
result_class_name, role, result_role, keys_only):
gen = self.enum_instances(env, model, keys_only)
for inst in gen:
for prop in inst.properties.values():
if prop.type != 'reference':
continue
if role and prop.name.lower() != role:
continue
if self.paths_equal(object_name, prop.value):
yield inst
def paths_equal(self, lhs, rhs):
"""If one object path doesn't inlcude a host, don't include the hosts
in the comparison
"""
if lhs is rhs:
return True
if lhs.host is not None and rhs.host is not None and lhs.host != rhs.host:
return False
# need to make sure this stays in sync with CIMInstanceName.__cmp__()
return not (pywbem.cmpname(rhs.classname, lhs.classname) or
cmp(rhs.keybindings, lhs.keybindings) or
pywbem.cmpname(rhs.namespace, lhs.namespace))
def MI_enumInstanceNames(self,
env,
objPath):
"""Return instance names of a given CIM class
Implements the WBEM operation EnumerateInstanceNames in terms
of the enum_instances method. A derived class will not normally
override this method.
"""
logger = env.get_logger()
logger.log_debug('CIMProvider2 MI_enumInstanceNames called...')
model = pywbem.CIMInstance(classname=objPath.classname,
path=objPath)
gen = self.enum_instances(env=env,
model=model,
keys_only=True)
try:
iter(gen)
except TypeError:
logger.log_debug('CIMProvider2 MI_enumInstanceNames returning')
return
for inst in gen:
yield inst.path
logger.log_debug('CIMProvider2 MI_enumInstanceNames returning')
def MI_enumInstances(self,
env,
objPath,
propertyList):
"""Return instances of a given CIM class
Implements the WBEM operation EnumerateInstances in terms
of the enum_instances method. A derived class will not normally
override this method.
"""
logger = env.get_logger()
logger.log_debug('CIMProvider2 MI_enumInstances called...')
model = pywbem.CIMInstance(classname=objPath.classname,
path=objPath)
gen = self.enum_instances(env=env,
model=model,
keys_only=False)
try:
iter(gen)
except TypeError:
logger.log_debug('CIMProvider2 MI_enumInstances returning')
return
return gen
def MI_getInstance(self,
env,
instanceName,
propertyList):
"""Return a specific CIM instance
Implements the WBEM operation GetInstance in terms
of the get_instance method. A derived class will not normally
override this method.
"""
logger = env.get_logger()
logger.log_debug('CIMProvider2 MI_getInstance called...')
plist = None
if propertyList is not None:
plist = [s.lower() for s in propertyList]
plist+= [s.lower() for s in instanceName.keybindings.keys()]
model = pywbem.CIMInstance(classname=instanceName.classname,
path=instanceName, property_list=plist)
model.update(model.path.keybindings)
rval = self.get_instance(env=env, model=model)
logger.log_debug('CIMProvider2 MI_getInstance returning')
if rval is None:
raise pywbem.CIMError(pywbem.CIM_ERR_NOT_FOUND, "")
return rval
def MI_createInstance(self,
env,
instance):
"""Create a CIM instance, and return its instance name
Implements the WBEM operation CreateInstance in terms
of the set_instance method. A derived class will not normally
override this method.
"""
logger = env.get_logger()
logger.log_debug('CIMProvider2 MI_createInstance called...')
rval = None
'''
ch = env.get_cimom_handle()
cimClass = ch.GetClass(instance.classname,
instance.path.namespace,
LocalOnly=False,
IncludeQualifiers=True)
'''
# CIMOM has already filled in default property values for
# props with default values, if values not supplied by client.
rval = self.set_instance(env=env,
instance=instance,
modify_existing=False)
logger.log_debug('CIMProvider2 MI_createInstance returning')
return rval.path
def MI_modifyInstance(self,
env,
modifiedInstance,
propertyList):
"""Modify a CIM instance
Implements the WBEM operation ModifyInstance in terms
of the set_instance method. A derived class will not normally
override this method.
"""
logger = env.get_logger()
logger.log_debug('CIMProvider2 MI_modifyInstance called...')
plist = None
if propertyList is not None:
plist = [s.lower() for s in propertyList]
plist+= [s.lower() for s in modifiedInstance.path.keybindings.keys()]
self.filter_instance(modifiedInstance, plist)
modifiedInstance.property_list = plist
modifiedInstance.update(modifiedInstance.path)
self.set_instance(env=env,
instance=modifiedInstance,
modify_existing=True)
logger.log_debug('CIMProvider2 MI_modifyInstance returning')
def MI_deleteInstance(self,
env,
instanceName):
"""Delete a CIM instance
Implements the WBEM operation DeleteInstance in terms
of the delete_instance method. A derived class will not normally
override this method.
"""
logger = env.get_logger()
logger.log_debug('CIMProvider2 MI_deleteInstance called...')
self.delete_instance(env=env, instance_name=instanceName)
logger.log_debug('CIMProvider2 MI_deleteInstance returning')
def MI_associators(self,
env,
objectName,
assocClassName,
resultClassName,
role,
resultRole,
propertyList):
"""Return instances associated to a given object.
Implements the WBEM operation Associators in terms
of the references method. A derived class will not normally
override this method.
"""
# NOTE: This should honor the parameters resultClassName, role, resultRole,
# and propertyList
logger = env.get_logger()
logger.log_debug('CIMProvider2 MI_associators called. assocClass: %s' % (assocClassName))
if not assocClassName:
raise pywbem.CIMError(pywbem.CIM_ERR_FAILED,
"Empty assocClassName passed to Associators")
ch = env.get_cimom_handle()
model = pywbem.CIMInstance(classname=assocClassName)
model.path = pywbem.CIMInstanceName(classname=assocClassName,
namespace=objectName.namespace)
gen = self.references(env=env,
object_name=objectName,
model=model,
result_class_name=resultClassName,
role=role,
result_role=None,
keys_only=False)
if gen is None:
logger.log_debug('references() returned None instead of generator object')
return
for inst in gen:
for prop in inst.properties.values():
lpname = prop.name.lower()
if prop.type != 'reference':
continue
if role and role.lower() == lpname:
continue
if resultRole and resultRole.lower() != lpname:
continue
if self.paths_equal(prop.value, objectName):
continue
if resultClassName and \
resultClassName.lower() != prop.value.classname.lower():
continue
try:
if prop.value.namespace is None:
prop.value.namespace = objectName.namespace
inst = ch.GetInstance(prop.value, propertyList)
except pywbem.CIMError, (num, msg):
if num == pywbem.CIM_ERR_NOT_FOUND:
continue
else:
raise
if inst.path is None:
inst.path = prop.value
yield inst
logger.log_debug('CIMProvider2 MI_associators returning')
def MI_associatorNames(self,
env,
objectName,
assocClassName,
resultClassName,
role,
resultRole):
"""Return instances names associated to a given object.
Implements the WBEM operation AssociatorNames in terms
of the references method. A derived class will not normally
override this method.
"""
logger = env.get_logger()
logger.log_debug('CIMProvider2 MI_associatorNames called. assocClass: %s' % (assocClassName))
if not assocClassName:
raise pywbem.CIMError(pywbem.CIM_ERR_FAILED,
"Empty assocClassName passed to AssociatorNames")
model = pywbem.CIMInstance(classname=assocClassName)
model.path = pywbem.CIMInstanceName(classname=assocClassName,
namespace=objectName.namespace)
gen = self.references(env=env,
object_name=objectName,
model=model,
result_class_name=resultClassName,
role=role,
result_role=None,
keys_only=False)
if gen is None:
logger.log_debug('references() returned None instead of generator object')
return
for inst in gen:
for prop in inst.properties.values():
lpname = prop.name.lower()
if prop.type != 'reference':
continue
if role and role.lower() == lpname:
continue
if resultRole and resultRole.lower() != lpname:
continue
if self.paths_equal(prop.value, objectName):
continue
if resultClassName and \
resultClassName.lower() != prop.value.classname.lower():
continue
if prop.value.namespace is None:
prop.value.namespace = objectName.namespace
yield prop.value
logger.log_debug('CIMProvider2 MI_associatorNames returning')
def MI_references(self,
env,
objectName,
resultClassName,
role,
propertyList):
"""Return instances of an association class.
Implements the WBEM operation References in terms
of the references method. A derived class will not normally
override this method.
"""
logger = env.get_logger()
logger.log_debug('CIMProvider2 MI_references called. resultClass: %s' % (resultClassName))
if not resultClassName:
raise pywbem.CIMError(pywbem.CIM_ERR_FAILED,
"Empty resultClassName passed to References")
plist = None
if propertyList is not None:
plist = [s.lower() for s in propertyList]
model = pywbem.CIMInstance(classname=resultClassName,
property_list=plist)
model.path = pywbem.CIMInstanceName(classname=resultClassName,
namespace=objectName.namespace)
if role:
if role not in model.properties:
raise pywbem.CIMError(pywbem.CIM_ERR_FAILED,
"** this shouldn't happen")
model[role] = objectName
gen = self.references(env=env,
object_name=objectName,
model=model,
result_class_name='',
role=role,
result_role=None,
keys_only=False)
if gen is None:
logger.log_debug('references() returned None instead of generator object')
return
for inst in gen:
for prop in inst.properties.values():
if hasattr(prop.value, 'namespace') and \
prop.value.namespace is None:
prop.value.namespace = objectName.namespace
yield inst
logger.log_debug('CIMProvider2 MI_references returning')
def MI_referenceNames(self,
env,
objectName,
resultClassName,
role):
"""Return instance names of an association class.
Implements the WBEM operation ReferenceNames in terms
of the references method. A derived class will not normally
override this method.
"""
logger = env.get_logger()
logger.log_debug('CIMProvider2 MI_referenceNames <2> called. resultClass: %s' % (resultClassName))
if not resultClassName:
raise pywbem.CIMError(pywbem.CIM_ERR_FAILED,
"Empty resultClassName passed to ReferenceNames")
model = pywbem.CIMInstance(classname=resultClassName)
model.path = pywbem.CIMInstanceName(classname=resultClassName,
namespace=objectName.namespace)
if role:
if role not in model.properties:
raise pywbem.CIMError(pywbem.CIM_ERR_FAILED,
"** this shouldn't happen")
model[role] = objectName
gen = self.references(env=env,
object_name=objectName,
model=model,
result_class_name='',
role=role,
result_role=None,
keys_only=True)
if gen is None:
logger.log_debug('references() returned None instead of generator object')
return
for inst in gen:
for prop in inst.properties.values():
if hasattr(prop.value, 'namespace') and prop.value.namespace is None:
prop.value.namespace = objectName.namespace
yield inst.path
logger.log_debug('CIMProvider2 MI_referenceNames returning')
def MI_invokeMethod(self, env, objectName, methodName, inputParams):
"""Invoke an extrinsic method.
Implements the InvokeMethod WBEM operation by calling the
method on a derived class called cim_method_<method_name>,
where <method_name> is the name of the CIM method, in all
lower case.
Arguments:
env -- Provider Environment (pycimmb.ProviderEnvironment)
objectName -- The InstanceName or ClassName of the object on
which the method is invoked.
methodName -- The name of the method to be invoked.
inputParams -- A Dictionary where the key is the parameter name
and the value is the parameter value.
The return value for invokeMethod must be a tuple of size 2
where:
element 0 is a tuple of size 2 where element 0 is the return
data type name and element 1 is the actual data value.
element 1 is a dictionary where the key is the output
parameter name and the value is a tuple of size 2 where
element 0 is the data type name for the output parameter
and element 1 is the actual value of the output parameter.
A derived class will not normally override this method.
"""
logger = env.get_logger()
logger.log_debug('CIMProvider2 MI_invokeMethod called. method: %s:%s' \
% (objectName.classname,methodName))
lmethName = "cim_method_%s" % methodName.lower()
if hasattr(self, lmethName) :
method = getattr(self, lmethName)
new_inputs = dict([('param_%s' % k.lower(), v) \
for k, v in inputParams.items()])
try:
(rval, outs) = method(env=env, object_name=objectName,
**new_inputs)
except TypeError, e:
raise pywbem.CIMError(pywbem.CIM_ERR_INVALID_PARAMETER, str(e))
def add_type(v):
if isinstance(v, pywbem.CIMParameter):
return (v.type, v.value)
lv = v
if type(v) == list and len(v) > 0:
lv = v[0]
if isinstance(lv, pywbem.CIMClass):
tp = 'class'
elif isinstance(lv, pywbem.CIMInstance):
tp = 'instance'
elif isinstance(lv, pywbem.CIMInstanceName):
tp = 'reference'
elif v is None or (type(v) == list and len(v) == 0):
assert(None == 'This should not happen')
else:
tp = pywbem.cimtype(v)
return (tp, v)
louts = {}
for op in outs:
louts[op.name] = (op.type, op.value)
rval = add_type(rval)
rval = (rval, louts)
else:
raise pywbem.CIMError(pywbem.CIM_ERR_METHOD_NOT_FOUND,
"%s:%s"%(objectName.classname, methodName))
logger.log_debug('CIMProvider2 MI_invokeMethod returning')
return rval
def filter_instance(self, inst, plist):
"""Remove properties from an instance that aren't in the PropertyList
inst -- The CIMInstance
plist -- The property List, or None. The list items must be all
lowercase.
"""
if plist is not None:
for pname in inst.properties.keys():
if pname.lower() not in plist and pname:
if inst.path is not None and pname in inst.path.keybindings:
continue
del inst.properties[pname]
def authorize_filter (env, filter, ns, classes,
owner):
"""Allow or disallow an indication subscription request.
Arguments:
env -- Provider Environment (pycimmb.ProviderEnvironment)
filter -- The WQL select statement
namespace -- The namepace where the indication is registered for
classes -- The classpath of the indication registered for
owner -- The name of the principal (cimom user)
"""
pass
def activate_filter (env, filter, ns, classes,
first_activation):
"""Activate an indication subscription.
Arguments:
env -- Provider Environment (pycimmb.ProviderEnvironment)
filter -- The WQL select statement
namespace -- The namepace where the indication is registered for
classes -- The classpath of the indication registered for
first_activation -- boolean - whether first activation
"""
pass
def deactivate_filter(env, filter, ns, classes,
last_activation):
"""Deactivate an indication subscription.
Arguments:
env -- Provider Environment (pycimmb.ProviderEnvironment)
filter -- The WQL select statement
ns -- The namepace where the indication is registered for
classes -- The classpath of the indication registered for
last_activation -- boolean - whether last activation
"""
pass
def enable_indications(env):
"""Enable indications.
Arguments:
env -- Provider Environment (pycimmb.ProviderEnvironment)
"""
pass
def disable_indications(env):
"""Disable indications.
Arguments:
env -- Provider Environment (pycimmb.ProviderEnvironment)
"""
pass
def codegen (cc):
"""Generate a Python Provider template.
Parameters:
cc - A CIMClass to generate code for.
Returns a two-tuple containing the Python provider code stubs, and
the provider registration MOF.
"""
import inspect
def format_desc (obj, indent):
linelen = 75 - indent
if isinstance(obj, basestring):
raw = obj
else:
try:
raw = obj.qualifiers['description'].value
except KeyError:
return ''
txt = ''
beg = 0
end = 0
while beg < len(raw):
beg = end
end += linelen
while beg < len(raw) and raw[beg].isspace():
beg = beg+1
while end < len(raw) and end > beg and not raw[end].isspace():
end = end-1
if beg == end: # a long URL
while end < len(raw) and not raw[end].isspace():
end+= 1
line = raw[beg:end]
line = line.replace('\n',' ')
line = line.replace('\r','')
txt += '\n%s%s'% (''.ljust(indent), line)
return txt
#################
def map_value(obj, val):
rv = str(val)
if 'ValueMap' not in obj.qualifiers:
return rv
if 'Values' not in obj.qualifiers:
return rv
vals = [str(x) for x in obj.qualifiers['Values'].value]
maps = [str(x) for x in obj.qualifiers['ValueMap'].value]
d = dict(zip(maps, vals))
try:
tmp = d[str(val)]
rv = ''
for ch in tmp:
rv+= ch.isalnum() and ch or '_'
except KeyError:
pass
return rv
#################
def type_hint (obj, method_name=None):
if hasattr(obj, 'type'):
tx = obj.type
if 'embeddedinstance' in obj.qualifiers:
tx = "pywbem.CIMInstance(classname='%s', ...)" % \
obj.qualifiers['embeddedinstance'].value
elif tx == 'reference':
tx = "pywbem.CIMInstanceName(classname='%s', ...)" % \
obj.reference_class
else:
tx = obj.return_type
if hasattr(obj, 'value') and obj.value is not None:
defval = str(obj.value)
else:
defval = ''
if not tx.startswith('pywbem.'):
if tx == 'boolean':
tx = 'bool(%s)' % defval
elif tx == 'datetime':
tx = 'pywbem.CIMDateTime()'
elif tx == 'string':
tx = "''"
else:
tx = 'pywbem.%s(%s)' % (tx.capitalize(), defval)
if 'valuemap' in obj.qualifiers:
if defval:
defval = map_value(obj, defval)
else:
defval = '<VAL>'
tx = 'self.Values.%s%s.%s' % \
(method_name and '%s.'%method_name or '',
obj.name, defval)
if hasattr(obj, 'is_array') and obj.is_array:
tx = '[%s,]' % tx
return tx
#################
def type_str (obj, method_name=None):
if hasattr(obj, 'type'):
tx = obj.type
if 'embeddedinstance' in obj.qualifiers:
return "pywbem.CIMInstance(classname='%s', ...)" % \
obj.qualifiers['embeddedinstance'].value
elif tx == 'reference':
return "REF (pywbem.CIMInstanceName(classname='%s', ...)" % \
obj.reference_class
else:
tx = obj.return_type
if tx == 'boolean':
tx = 'bool'
elif tx == 'datetime':
tx = 'pywbem.CIMDateTime'
elif tx == 'string':
tx = 'unicode'
else:
tx = 'pywbem.%s' % tx.capitalize()
if hasattr(obj, 'is_array') and obj.is_array:
tx = '[%s,]' % tx
if 'valuemap' in obj.qualifiers:
tx+= ' self.Values.%s%s' % \
(method_name and '%s.'%method_name or '',obj.name)
return tx
#################
def is_required (obj):
if 'required' in obj.qualifiers and obj.qualifiers['required'].value:
return '(Required)'
return ''
#################
def build_val_map(obj):
vm = obj.qualifiers['valuemap'].value
if 'values' in obj.qualifiers:
vals = obj.qualifiers['values'].value
else:
vals = vm
tmap = zip(vals,vm)
map = []
for t in tmap:
nname = ''
for ch in t[0]:
if ch.isalnum():
nname+= ch
else:
nname+= '_'
if hasattr(obj, 'return_type'):
tp = obj.return_type
else:
tp = obj.type
if tp == 'string':
val = "'%s'" % t[1]
else:
try:
int(t[1])
val = 'pywbem.%s(%s)' % (tp.capitalize(), t[1])
except ValueError:
val = t[1]
nname = "# "+nname
map.append((nname,val))
return map
valuemaps = {}
for obj in cc.properties.values() + cc.methods.values():
if 'valuemap' in obj.qualifiers:
valuemaps[obj.name] = {'<vms>':build_val_map(obj)}
for meth in cc.methods.values():
for parm in meth.parameters.values():
if 'valuemap' in parm.qualifiers:
if meth.name not in valuemaps:
valuemaps[meth.name] = {}
valuemaps[meth.name][parm.name] = build_val_map(parm)
mappings = {'classname':cc.classname,
'classname_l':cc.classname.lower()}
isAssoc = 'association' in cc.qualifiers
isIndication = 'indication' in cc.qualifiers
code = '''"""Python Provider for %(classname)s
Instruments the CIM class %(classname)s
"""
import pywbem
from pywbem.cim_provider2 import CIMProvider2
class %(classname)s(CIMProvider2):
"""Instrument the CIM class %(classname)s \n''' % mappings
code+= format_desc(cc, 4)
code+= '''
"""'''
args = inspect.getargspec(CIMProvider2.get_instance)[0]
args = ', '.join(args)
code+= '''
def __init__ (self, env):
logger = env.get_logger()
logger.log_debug('Initializing provider %%s from %%s' \\
%% (self.__class__.__name__, __file__))
def get_instance(%s):
"""%s"""
logger = env.get_logger()
logger.log_debug('Entering %%s.get_instance()' \\
%% self.__class__.__name__)
''' % (args, CIMProvider2.get_instance.__doc__ )
keyProps = [p for p in cc.properties.values() \
if 'key' in p.qualifiers]
if not keyProps and 'association' in cc.qualifiers:
# SFCB has problems with qualifiers on REF properties.
# http://sourceforge.net/tracker/index.php?func=detail&aid=2104565&group_id=128809&atid=712784
keyProps = [p for p in cc.properties.values() \
if p.type == 'reference']
for prop in keyProps:
prop.qualifiers['KEY'] = True
code+= '''
# TODO fetch system resource matching the following keys:'''
for kp in keyProps:
code+= '''
# model['%s']''' % kp.name
code+= '\n'
props = cc.properties.values()
props.sort()
for prop in props:
if 'key' in prop.qualifiers:
continue
line = "#model['%s'] = %s # TODO %s" % \
(prop.name, type_hint(prop), is_required(prop))
code+= '''
%s''' % line
args = inspect.getargspec(CIMProvider2.enum_instances)[0]
args = ', '.join(args)
code+= '''
return model
def enum_instances(%s):
"""%s"""
logger = env.get_logger()
logger.log_debug('Entering %%s.enum_instances()' \\
%% self.__class__.__name__)
''' % (args, CIMProvider2.enum_instances.__doc__)
keydict = dict([(str(kp.name), None) for kp in keyProps])
code+= '''
# Prime model.path with knowledge of the keys, so key values on
# the CIMInstanceName (model.path) will automatically be set when
# we set property values on the model.
model.pa%s
''' % format_desc('th.update('+str(keydict)+')', 12).strip()
code+= '''
while False: # TODO more instances?
# TODO fetch system resource
# Key properties'''
for kp in keyProps:
if kp.name == 'CreationClassName':
line = "model['%s'] = '%s'" % (kp.name, cc.classname)
else:
line = "#model['%s'] = %s # TODO (type = %s)" % \
(kp.name, type_hint(kp), type_str(kp))
code+='''
%s''' % line
code+='''
if keys_only:
yield model
else:
try:
yield self.get_instance(env, model)
except pywbem.CIMError, (num, msg):
if num not in (pywbem.CIM_ERR_NOT_FOUND,
pywbem.CIM_ERR_ACCESS_DENIED):
raise\n'''
args = inspect.getargspec(CIMProvider2.set_instance)[0]
args = ', '.join(args)
code+= '''
def set_instance(%s):
"""%s"""
logger = env.get_logger()
logger.log_debug('Entering %%s.set_instance()' \\
%% self.__class__.__name__)
# TODO create or modify the instance
raise pywbem.CIMError(pywbem.CIM_ERR_NOT_SUPPORTED) # Remove to implement
return instance''' % (args, CIMProvider2.set_instance.__doc__)
args = inspect.getargspec(CIMProvider2.delete_instance)[0]
args = ', '.join(args)
code+= '''
def delete_instance(%s):
"""%s"""
logger = env.get_logger()
logger.log_debug('Entering %%s.delete_instance()' \\
%% self.__class__.__name__)
# TODO delete the resource
raise pywbem.CIMError(pywbem.CIM_ERR_NOT_SUPPORTED) # Remove to implement
''' % (args, CIMProvider2.delete_instance.__doc__)
for method in cc.methods.values():
inParms = [ p for p in method.parameters.values() if \
'in' in p.qualifiers and p.qualifiers['in'].value ]
outParms = [ p for p in method.parameters.values() if \
'out' in p.qualifiers and p.qualifiers['out'].value ]
code+= '''
def cim_method_%s(self, env, object_name''' % method.name.lower()
for p in inParms:
if 'required' in p.qualifiers and p.qualifiers['required']:
code+= ''',\n%sparam_%s''' % (''.rjust(len(method.name)+20),
p.name.lower())
for p in inParms:
if 'required' not in p.qualifiers or not p.qualifiers['required']:
code+= ''',\n%sparam_%s=None'''%\
(''.rjust(len(method.name)+20),
p.name.lower())
code+= '''):
"""Implements %s.%s()\n''' % (cc.classname, method.name)
code+= format_desc(method, 8)
code+= '''
Keyword arguments:
env -- Provider Environment (pycimmb.ProviderEnvironment)
object_name -- A pywbem.CIMInstanceName or pywbem.CIMCLassName
specifying the object on which the method %s()
should be invoked.'''\
% method.name
for p in inParms:
code+= '''
param_%s -- The input parameter %s (type %s) %s''' \
% (p.name.lower(), p.name, type_str(p, method.name),
is_required(p))
code+= format_desc(p, 12)
code+='''
Returns a two-tuple containing the return value (type %s)
and a list of CIMParameter objects representing the output parameters
Output parameters:''' % type_str(method)
if not outParms:
code+= ' none'
else:
for p in outParms:
code+='''
%s -- (type %s) %s''' % (p.name, type_str(p, method.name),
is_required(p))
code+= format_desc(p, 12)
code+='''
Possible Errors:
CIM_ERR_ACCESS_DENIED
CIM_ERR_INVALID_PARAMETER (including missing, duplicate,
unrecognized or otherwise incorrect parameters)
CIM_ERR_NOT_FOUND (the target CIM Class or instance does not
exist in the specified namespace)
CIM_ERR_METHOD_NOT_AVAILABLE (the CIM Server is unable to honor
the invocation request)
CIM_ERR_FAILED (some other unspecified error occurred)
"""
logger = env.get_logger()
logger.log_debug('Entering %%s.cim_method_%s()' \\
%% self.__class__.__name__)
# TODO do something
raise pywbem.CIMError(pywbem.CIM_ERR_METHOD_NOT_AVAILABLE) # Remove to implemented
out_params = []''' % method.name.lower()
for p in outParms:
code+='''
#out_params+= [pywbem.CIMParameter('%s', type='%s',
# value=%s)] # TODO''' % (p.name.lower(), p.type,
type_hint(p, method.name))
code+='''
#rval = # TODO (type %s)
return (rval, out_params)
''' % type_str(method)
if isAssoc:
args = inspect.getargspec(CIMProvider2.references)[0]
args = format_desc(', '.join(args), 19).strip()
code+= '''
def references(%s):
"""%s"""
logger = env.get_logger()
logger.log_debug('Entering %%s.references()' \\
%% self.__class__.__name__)
ch = env.get_cimom_handle()''' % \
(args, CIMProvider2.references.__doc__)
refprops = []
for prop in cc.properties.values():
if prop.reference_class is not None:
refprops.append((prop.name, prop.reference_class))
code+= '''\n
# If you want to get references for free, implemented in terms
# of enum_instances, just leave the code below unaltered.'''
for i, refprop in enumerate(refprops):
if i == 0:
code+= '''
if ch.is_subclass(object_name.namespace,
sub=object_name.classname,
super='%s')''' % refprop[1]
else:
code+= ''' or \\
ch.is_subclass(object_name.namespace,
sub=object_name.classname,
super='%s')''' % refprop[1]
code+=''':
return self.simple_refs(env, object_name, model,
result_class_name, role, result_role, keys_only)
'''
code+='''
# If you are doing simple refs with the code above, remove the
# remainder of this method. Or, remove the stuff above and
# implement references below. You need to pick either the
# above approach or the below, and delete the other. Otherwise
# you'll get a SyntaxError on the first yield below.
# Prime model.path with knowledge of the keys, so key values on
# the CIMInstanceName (model.path) will automatically be set when
# we set property values on the model.
model.pa%s
# This is a common pattern. YMMV''' % \
format_desc('th.update('+str(keydict)+')', 12).strip()
for refprop in refprops:
code+= '''
if (not role or role.lower() == '%(refpropnamel)s') and \\
ch.is_subclass(object_name.namespace,
sub=object_name.classname,
super='%(rolecname)s'):
model['%(refpropname)s'] = object_name
yield model # TODO: Add other REF properties.
# Yield association instances where
# object_name is %(refpropnamel)s.
# Only appropriate if object_name.classname
# is '%(rolecname)s' or a subclass.\n''' \
% {'refpropname':refprop[0],
'refpropnamel':refprop[0].lower(),
'rolecname':refprop[1]}
if valuemaps:
code+= '''
class Values(object):'''
for group, maps in valuemaps.items():
code+= '''
class %s(object):''' % group
if '<vms>' in maps:
for value, vm in maps['<vms>']:
if value in maps:
value = value+'_'
code+= '''
%s = %s''' % (value, vm)
for pname, vms in maps.items():
if pname == '<vms>':
continue
code+= '''
class %s(object):''' % pname
for value, vm in vms:
code+= '''
%s = %s''' % (value, vm)
code+= '\n'
code+= '''
## end of class %(classname)sProvider
## get_providers() for associating CIM Class Name to python provider class name
def get_providers(env):
%(classname_l)s_prov = %(classname)s(env)
return {'%(classname)s': %(classname_l)s_prov}
''' % mappings
if isIndication:
code+= '''
## Indication support methods...
## Use these methods if this class will deliver indications.
## Remove these methods if this class will not deliver indications.'''
args = inspect.getargspec(CIMProvider2.authorize_filter)[0]
args = format_desc(', '.join(args), 19).strip()
code+= '''
def authorize_filter(%s):
"""%s"""
logger = env.get_logger()
logger.log_debug('Entering %%s.authorize_filter()' \\
%% self.__class__.__name__)
ch = env.get_cimom_handle()
#raise pywbem.CIMError(pywbem.CIM_ERR_***) to indicate failure
#otherwise just fall through for success''' % \
(args, CIMProvider2.authorize_filter.__doc__ or "Doc Goes Here")
args = inspect.getargspec(CIMProvider2.enable_indications)[0]
args = format_desc(', '.join(args), 19).strip()
code+= '''
def enable_indications(%s):
"""%s"""
logger = env.get_logger()
logger.log_debug('Entering %%s.enable_indications()' \\
%% self.__class__.__name__)
ch = env.get_cimom_handle()
#raise pywbem.CIMError(pywbem.CIM_ERR_***) to indicate failure
#otherwise just fall through for success''' % \
(args, CIMProvider2.enable_indications.__doc__ or "Doc Goes Here")
args = inspect.getargspec(CIMProvider2.disable_indications)[0]
args = format_desc(', '.join(args), 19).strip()
code+= '''
def disable_indications(%s):
"""%s"""
logger = env.get_logger()
logger.log_debug('Entering %%s.disable_indications()' \\
%% self.__class__.__name__)
ch = env.get_cimom_handle()
#raise pywbem.CIMError(pywbem.CIM_ERR_***) to indicate failure
#otherwise just fall through for success''' % \
(args, CIMProvider2.disable_indications.__doc__ or "Doc Goes Here")
args = inspect.getargspec(CIMProvider2.activate_filter)[0]
args = format_desc(', '.join(args), 19).strip()
code+= '''
def activate_filter(%s):
"""%s"""
logger = env.get_logger()
logger.log_debug('Entering %%s.activate_filter()' \\
%% self.__class__.__name__)
ch = env.get_cimom_handle()
#raise pywbem.CIMError(pywbem.CIM_ERR_***) to indicate failure
#otherwise just fall through for success''' % \
(args, CIMProvider2.activate_filter.__doc__ or "Doc Goes Here")
args = inspect.getargspec(CIMProvider2.deactivate_filter)[0]
args = format_desc(', '.join(args), 19).strip()
code+= '''
def deactivate_filter(%s):
"""%s"""
logger = env.get_logger()
logger.log_debug('Entering %%s.deactivate_filter()' \\
%% self.__class__.__name__)
ch = env.get_cimom_handle()
#raise pywbem.CIMError(pywbem.CIM_ERR_***) to indicate failure
#otherwise just fall through for success''' % \
(args, CIMProvider2.deactivate_filter.__doc__ or "Doc Goes Here")
code+= '''
## End of Indication Support Methods'''
owtypes = ['1', 'Instance']
pegtypes = ['2', 'Instance']
sfcbtypes = 'instance'
if isAssoc:
owtypes[0]+= ',3'
owtypes[1]+= ', Associator'
pegtypes[0]+= ',3'
pegtypes[1]+= ', Associator'
sfcbtypes+= ' association'
if cc.methods:
owtypes[0]+= ',6'
owtypes[1]+= ', Method'
pegtypes[0]+= ',5'
pegtypes[1]+= ', Method'
sfcbtypes+= ' method'
omitted = '''
// OpenWBEM Provider registration for %(classname)s
instance of OpenWBEM_PyProviderRegistration
{
InstanceID = "<org:product:%(classname)s:unique_id>"; // TODO
NamespaceNames = {"root/cimv2"}; // TODO
ClassName = "%(classname)s";
ProviderTypes = {%(owtypeNums)s}; // %(owtypeStrs)s
ModulePath = "/usr/lib/pycim/%(classname)sProvider.py"; // TODO
};
'''
mof ='''
// SFCB Provider registration for %(classname)s
[%(classname)s]
provider: %(classname)s
location: pyCmpiProvider
type: %(sfcbtypes)s
namespace: root/cimv2 // TODO
// Pegasus Provider registration for %(classname)s
instance of PG_ProviderModule
{
Name = "pyCmpiProvider_%(classname)s";
InterfaceType = "CMPI";
InterfaceVersion = "2.0.0";
Location = "pyCmpiProvider";
UserContext = 2; // Requestor
Vendor = "TODO"; // TODO
Version = "1.0";
};
instance of PG_Provider
{
Name = "%(classname)s";
ProviderModuleName = "pyCmpiProvider_%(classname)s";
};
instance of PG_ProviderCapabilities
{
CapabilityID = "%(classname)s";
ProviderModuleName = "pyCmpiProvider_%(classname)s";
ProviderName = "%(classname)s";
ClassName = "%(classname)s";
Namespaces = {"root/cimv2"}; // TODO
ProviderType = {%(pegtypeNum)s}; // %(pegtypeStr)s
};\n''' % {'classname': cc.classname,
'owtypeNums': owtypes[0],
'owtypeStrs': owtypes[1],
'pegtypeNum': pegtypes[0],
'pegtypeStr': pegtypes[1],
'sfcbtypes' : sfcbtypes}
return code, mof
class ProviderProxy(object):
"""Wraps a provider module, and routes requests into the module """
def __init__ (self, env, provid):
self.env = env
if isinstance(provid, types.ModuleType):
self.provmod = provid
self.provid = provid.__name__
self.filename = provid.__file__
else:
logger = env.get_logger()
logger.log_debug('Loading python provider at %s' %provid)
self.provid = provid
self._load_provider_source()
self._init_provider(env)
def _init_provider (self, env):
self.provregs = {}
if hasattr(self.provmod, 'init'):
self.provmod.init(env)
if hasattr(self.provmod, 'get_providers'):
self.provregs = pywbem.NocaseDict(self.provmod.get_providers(env))
def _load_provider_source (self):
# odd chars in a module name tend to break things
self.provider_module_name = 'pyprovider_'
for ch in self.provid:
self.provider_module_name+= ch.isalnum() and ch or '_'
# let providers import other providers in the same directory
provdir = dirname(self.provid)
if provdir not in sys.path:
sys.path.append(provdir)
try:
self.provmod = sys.modules[self.provider_module_name]
print 'Provider %s already loaded, found in sys.modules' \
% self.provmod
except KeyError:
try:
# use full path in module name for uniqueness.
print 'Loading provider %s from source' % self.provid
path = os.path.dirname(self.provid)
basename = os.path.basename(self.provid)[:-3]
fn = imp.find_module(basename, [path])
try:
g_mod_lock.acquire()
imp.acquire_lock()
self.provmod = imp.load_module(
self.provider_module_name, *fn)
self.provmod.provmod_timestamp = \
os.path.getmtime(self.provid)
finally:
imp.release_lock()
g_mod_lock.release()
fn[0].close()
except IOError, arg:
raise pywbem.CIMError(pywbem.CIM_ERR_FAILED,
"Error loading provider %s: %s" % (self.provid, arg))
self.filename = self.provmod.__file__
def _get_callable (self, classname, cname):
"""Return a function or method object appropriate to fulfill a request
classname -- The CIM class name associated with the request.
cname -- The function or method name to look for.
"""
callable = None
if classname in self.provregs:
provClass = self.provregs[classname]
if hasattr(provClass, cname):
callable = getattr(provClass, cname)
elif hasattr(self.provmod, cname):
callable = getattr(self.provmod, cname)
if callable is None:
raise pywbem.CIMError(pywbem.CIM_ERR_FAILED,
"No provider registered for %s or no callable for %s:%s on provider %s"%(classname, classname,
cname,
self.provid))
return callable
def _reload_if_necessary (self, env):
"""Check timestamp of loaded python provider module, and if it has
changed since load, then reload the provider module.
"""
try:
mod = sys.modules[self.provider_module_name]
except KeyError:
mod = None
if (mod is None or \
mod.provmod_timestamp != os.path.getmtime(self.provid)):
print "Need to reload provider at %s" %self.provid
#first unload the module
if self.provmod and hasattr(self.provmod, "shutdown"):
self.provmod.shutdown(env)
#now reload and reinit module
try:
del sys.modules[self.provider_module_name]
except KeyError:
pass
try:
self._load_provider_source()
self._init_provider(env)
except IOError, arg:
raise pywbem.CIMError(pywbem.CIM_ERR_FAILED,
"Error loading provider %s: %s" % (provid, arg))
##############################################################################
# enumInstanceNames
##############################################################################
def MI_enumInstanceNames (self,
env,
objPath):
logger = env.get_logger()
logger.log_debug('ProviderProxy MI_enumInstanceNames called...')
self._reload_if_necessary(env)
return self._get_callable(objPath.classname,
'MI_enumInstanceNames')(env, objPath)
##############################################################################
# enumInstances
##############################################################################
def MI_enumInstances(self,
env,
objPath,
propertyList):
logger = env.get_logger()
logger.log_debug('CIMProvider2 MI_enumInstances called...')
self._reload_if_necessary(env)
return self._get_callable(objPath.classname, 'MI_enumInstances') \
(env,
objPath,
propertyList)
##############################################################################
# getInstance
##############################################################################
def MI_getInstance(self,
env,
instanceName,
propertyList):
logger = env.get_logger()
logger.log_debug('CIMProvider2 MI_getInstance called...')
self._reload_if_necessary(env)
rval = self._get_callable(instanceName.classname, 'MI_getInstance') \
(env,
instanceName,
propertyList)
logger.log_debug('CIMProvider2 MI_getInstance returning')
return rval
##############################################################################
# createInstance
##############################################################################
def MI_createInstance(self,
env,
instance):
logger = env.get_logger()
logger.log_debug('CIMProvider2 MI_createInstance called...')
self._reload_if_necessary(env)
rval = self._get_callable(instance.classname, 'MI_createInstance') \
(env, instance)
logger.log_debug('CIMProvider2 MI_createInstance returning')
return rval
##############################################################################
# modifyInstance
##############################################################################
def MI_modifyInstance(self,
env,
modifiedInstance,
propertyList):
logger = env.get_logger()
logger.log_debug('CIMProvider2 MI_modifyInstance called...')
self._reload_if_necessary(env)
self._get_callable(modifiedInstance.classname, 'MI_modifyInstance') \
(env, modifiedInstance, propertyList)
logger.log_debug('CIMProvider2 MI_modifyInstance returning')
##############################################################################
# deleteInstance
##############################################################################
def MI_deleteInstance(self,
env,
instanceName):
logger = env.get_logger()
logger.log_debug('CIMProvider2 MI_deleteInstance called...')
self._reload_if_necessary(env)
self._get_callable(instanceName.classname, 'MI_deleteInstance') \
(env, instanceName)
logger.log_debug('CIMProvider2 MI_deleteInstance returning')
##############################################################################
# associators
##############################################################################
def MI_associators(self,
env,
objectName,
assocClassName,
resultClassName,
role,
resultRole,
propertyList):
# NOTE: This should honor the parameters resultClassName, role, resultRole,
# and propertyList
logger = env.get_logger()
logger.log_debug('CIMProvider2 MI_associators called. assocClass: %s' % (assocClassName))
self._reload_if_necessary(env)
cname = assocClassName
if not cname and hasattr(self.provmod, 'MI_associators'):
for i in self.provmod.MI_associators(
env,
objectName,
assocClassName,
resultClassName,
role,
resultRole,
propertyList):
yield i
return
lcnames = []
if cname:
lcnames = [cname]
else:
lcnames = self.provregs.keys()
for lcname in lcnames:
fn = self._get_callable(lcname, 'MI_associators')
for i in fn(env,
objectName,
lcname,
resultClassName,
role,
resultRole,
propertyList):
yield i
logger.log_debug('CIMProvider2 MI_associators returning')
##############################################################################
# associatorNames
##############################################################################
def MI_associatorNames(self,
env,
objectName,
assocClassName,
resultClassName,
role,
resultRole):
logger = env.get_logger()
logger.log_debug('CIMProvider2 MI_associatorNames called. assocClass: %s' % (assocClassName))
self._reload_if_necessary(env)
cname = assocClassName
if not cname and hasattr(self.provmod, 'MI_associatorNames'):
for i in self.provmod.MI_associatorNames(
env,
objectName,
assocClassName,
resultClassName,
role,
resultRole):
yield i
return
lcnames = []
if cname:
lcnames = [cname]
else:
lcnames = self.provregs.keys()
for lcname in lcnames:
fn = self._get_callable(lcname, 'MI_associatorNames')
for i in fn(env,
objectName,
lcname,
resultClassName,
role,
resultRole):
yield i
logger.log_debug('CIMProvider2 MI_associatorNames returning')
##############################################################################
# references
##############################################################################
def MI_references(self,
env,
objectName,
resultClassName,
role,
propertyList):
logger = env.get_logger()
logger.log_debug('CIMProvider2 MI_references called. resultClass: %s' % (resultClassName))
self._reload_if_necessary(env)
cname = resultClassName
if not cname and hasattr(self.provmod, 'MI_references'):
for i in self.provmod.MI_references(env, objectName,
resultClassName, role, propertyList):
yield i
return
lcnames = []
if cname:
lcnames = [cname]
else:
lcnames = self.provregs.keys()
for lcname in lcnames:
fn = self._get_callable(lcname, 'MI_references')
for i in fn(env,
objectName,
lcname,
role,
propertyList):
yield i
logger.log_debug('CIMProvider2 MI_references returning')
##############################################################################
# referenceNames
##############################################################################
def MI_referenceNames(self,
env,
objectName,
resultClassName,
role):
logger = env.get_logger()
logger.log_debug('CIMProvider2 MI_referenceNames <1> called. resultClass: %s' % (resultClassName))
self._reload_if_necessary(env)
cname = resultClassName
if not cname and hasattr(self.provmod, 'MI_referenceNames'):
for i in self.provmod.MI_referenceNames(env, objectName,
resultClassName, role):
yield i
return
lcnames = []
if cname:
lcnames = [cname]
else:
lcnames = self.provregs.keys()
for lcname in lcnames:
fn = self._get_callable(lcname, 'MI_referenceNames')
for i in fn(env,
objectName,
lcname,
role):
yield i
logger.log_debug('CIMProvider2 MI_referenceNames returning')
##############################################################################
# invokeMethod
# inputParam is a Dictionary where the key is the parameter name
# and the value is the parameter value
# The return value for invokeMethod must be a tuple of size 2 where
# element 0 is a tuple of size 2 where element 0 is the return data type name
# and element 1 is the actual data value
# element 1 is a dictionary where the key is the output parameter name
# and the value is a tuple of size 2 where element 0 is the data type name
# for the output parameter and element 1 is the actual value of the
# output parameter.
##############################################################################
def MI_invokeMethod(self, env, objectName, methodName, inputParams):
logger = env.get_logger()
logger.log_debug('CIMProvider2 MI_invokeMethod called. method: %s:%s' \
% (objectName.classname,methodName))
self._reload_if_necessary(env)
rval = self._get_callable(objectName.classname, 'MI_invokeMethod') \
(env, objectName, methodName, inputParams)
logger.log_debug('CIMProvider2 MI_invokeMethod returning')
return rval
##############################################################################
def MI_authorizeFilter (self,
env,
filter,
classname,
classPath,
owner):
logger = env.get_logger()
logger.log_debug('CIMProvider2 MI_authorizeFilter called')
self._reload_if_necessary(env)
if hasattr(self.provmod, 'authorize_filter'):
self.provmod.authorize_filter(env, filter, classname,
classPath, owner)
elif hasattr(self.provmod, 'MI_authorizeFilter'):
self.provmod.MI_authorizeFilter(env, filter, classname,
classPath, owner)
else:
# if not instrumented in provider, assume success
logger.log_debug("Provider %s has no support for authorize filter"%self.provid)
logger.log_debug('CIMProvider2 MI_authorizeFilter returning')
return
##############################################################################
def MI_activateFilter (self,
env,
filter,
namespace,
classes,
firstActivation):
logger = env.get_logger()
logger.log_debug('CIMProvider2 MI_activateFilter called')
self._reload_if_necessary(env)
if hasattr(self.provmod, 'activate_filter'):
self.provmod.activate_filter(env, filter, namespace,
classes, firstActivation)
elif hasattr(self.provmod, 'MI_activateFilter'):
self.provmod.MI_activateFilter(env, filter, namespace,
classes, firstActivation)
else:
# if not instrumented in provider, assume success
logger.log_debug("Provider %s has no support for activate filter"%self.provid)
logger.log_debug('CIMProvider2 MI_activateFilter returning')
return
##############################################################################
def MI_deActivateFilter(self,
env,
filter,
namespace,
classes,
lastActivation):
logger = env.get_logger()
logger.log_debug('CIMProvider2 MI_deActivateFilter called')
self._reload_if_necessary(env)
if hasattr(self.provmod, 'deactivate_filter'):
self.provmod.deactivate_filter(env, filter, namespace, classes,
lastActivation)
elif hasattr(self.provmod, 'MI_deActivateFilter'):
self.provmod.MI_deActivateFilter(env, filter, namespace, classes,
lastActivation)
else:
# if not instrumented in provider, assume success
logger.log_debug("Provider %s has no support for deactivate filter"%self.provid)
logger.log_debug('CIMProvider2 MI_deActivateFilter returning')
return
##############################################################################
def MI_enableIndications(self,
env):
logger = env.get_logger()
logger.log_debug('CIMProvider2 MI_enableIndications called')
self._reload_if_necessary(env)
if hasattr(self.provmod, 'enable_indications'):
self.provmod.enable_indications(env)
elif hasattr(self.provmod, 'MI_enableIndications'):
self.provmod.MI_enableIndications(env)
else:
# if not instrumented in provider, assume success
logger.log_debug("Provider %s has no support for enable indications"%self.provid)
logger.log_debug('CIMProvider2 MI_enableIndications returning')
return
##############################################################################
def MI_disableIndications(self,
env):
logger = env.get_logger()
logger.log_debug('CIMProvider2 MI_disableIndications called')
self._reload_if_necessary(env)
if hasattr(self.provmod, 'disable_indications'):
self.provmod.disable_indications(env)
elif hasattr(self.provmod, 'MI_disableIndications'):
self.provmod.MI_disableIndications(env)
else:
# if not instrumented in provider, assume success
logger.log_debug("Provider %s has no support for disable indications"%self.provid)
logger.log_debug('CIMProvider2 MI_disableIndications returning')
return
##############################################################################
def MI_shutdown (self, env):
modname = self.provmod.__name__
if hasattr(self.provmod, "shutdown"):
self.provmod.shutdown(env)
self.provmod = None
del sys.modules[modname]
#TODO concurrency problems here??
##############################################################################
def MI_canunload(self, env):
if hasattr(self.provmod, "canunload"):
return self.provmod.canunload
else:
return True
##############################################################################
def MI_consumeIndication(self,
env,
destinationPath,
indicationInstance):
logger = env.get_logger()
logger.log_debug('ProviderProxy MI_consumeIndication called')
self._reload_if_necessary(env)
if hasattr(self.provmod, 'consume_indication'):
self.provmod.consume_indication(env, destinationPath,
indicationInstance)
elif hasattr(self.provmod, 'MI_consumeIndication'):
self.provmod.MI_consumeIndication(env, destinationPath,
indicationInstance)
else:
raise pywbem.CIMError(pywbem.CIM_ERR_FAILED,
"Provider %s has no support for consume indication" % \
self.provid)
logger.log_debug('ProviderProxy MI_consumeIndication returning')
##############################################################################
def MI_handleIndication(self,
env,
ns,
handlerInstance,
indicationInstance):
logger = env.get_logger()
logger.log_debug('ProviderProxy MI_handleIndication called')
self._reload_if_necessary(env)
if hasattr(self.provmod, 'handle_indication'):
self.provmod.handle_indication(env, ns, handlerInstance,
indicationInstance)
elif hasattr(self.provmod, 'MI_handleIndication'):
self.provmod.MI_handleIndication(env, ns, handlerInstance,
indicationInstance)
else:
raise pywbem.CIMError(pywbem.CIM_ERR_FAILED,
"Provider %s has no support for handle indication"%self.provid)
logger.log_debug('ProviderProxy MI_handleIndication returning')
|