aboutsummaryrefslogtreecommitdiffstats
path: root/package/libs/libnl-tiny/src/include/linux/netlink.h
blob: d252103d2b7d9f598f92c2beb8e8e030880c3e61 (plain)
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
#ifndef __LINUX_NETLINK_H
#define __LINUX_NETLINK_H

#include <linux/socket.h> /* for sa_family_t */
#include <linux/types.h>

#define NETLINK_ROUTE		0	/* Routing/device hook				*/
#define NETLINK_UNUSED		1	/* Unused number				*/
#define NETLINK_USERSOCK	2	/* Reserved for user mode socket protocols 	*/
#define NETLINK_FIREWALL	3	/* Firewalling hook				*/
#define NETLINK_INET_DIAG	4	/* INET socket monitoring			*/
#define NETLINK_NFLOG		5	/* netfilter/iptables ULOG */
#define NETLINK_XFRM		6	/* ipsec */
#define NETLINK_SELINUX		7	/* SELinux event notifications */
#define NETLINK_ISCSI		8	/* Open-iSCSI */
#define NETLINK_AUDIT		9	/* auditing */
#define NETLINK_FIB_LOOKUP	10	
#define NETLINK_CONNECTOR	11
#define NETLINK_NETFILTER	12	/* netfilter subsystem */
#define NETLINK_IP6_FW		13
#define NETLINK_DNRTMSG		14	/* DECnet routing messages */
#define NETLINK_KOBJECT_UEVENT	15	/* Kernel messages to userspace */
#define NETLINK_GENERIC		16
/* leave room for NETLINK_DM (DM Events) */
#define NETLINK_SCSITRANSPORT	18	/* SCSI Transports */
#define NETLINK_ECRYPTFS	19

#define MAX_LINKS 32		

struct sockaddr_nl
{
	sa_family_t	nl_family;	/* AF_NETLINK	*/
	unsigned short	nl_pad;		/* zero		*/
	__u32		nl_pid;		/* port ID	*/
       	__u32		nl_groups;	/* multicast groups mask */
};

struct nlmsghdr
{
	__u32		nlmsg_len;	/* Length of message including header */
	__u16		nlmsg_type;	/* Message content */
	__u16		nlmsg_flags;	/* Additional flags */
	__u32		nlmsg_seq;	/* Sequence number */
	__u32		nlmsg_pid;	/* Sending process port ID */
};

/* Flags values */

#define NLM_F_REQUEST		1	/* It is request message. 	*/
#define NLM_F_MULTI		2	/* Multipart message, terminated by NLMSG_DONE */
#define NLM_F_ACK		4	/* Reply with ack, with zero or error code */
#define NLM_F_ECHO		8	/* Echo this request 		*/

/* Modifiers to GET request */
#define NLM_F_ROOT	0x100	/* specify tree	root	*/
#define NLM_F_MATCH	0x200	/* return all matching	*/
#define NLM_F_ATOMIC	0x400	/* atomic GET		*/
#define NLM_F_DUMP	(NLM_F_ROOT|NLM_F_MATCH)

/* Modifiers to NEW request */
#define NLM_F_REPLACE	0x100	/* Override existing		*/
#define NLM_F_EXCL	0x200	/* Do not touch, if it exists	*/
#define NLM_F_CREATE	0x400	/* Create, if it does not exist	*/
#define NLM_F_APPEND	0x800	/* Add to end of list		*/

/*
   4.4BSD ADD		NLM_F_CREATE|NLM_F_EXCL
   4.4BSD CHANGE	NLM_F_REPLACE

   True CHANGE		NLM_F_CREATE|NLM_F_REPLACE
   Append		NLM_F_CREATE
   Check		NLM_F_EXCL
 */

#define NLMSG_ALIGNTO	4
#define NLMSG_ALIGN(len) ( ((len)+NLMSG_ALIGNTO-1) & ~(NLMSG_ALIGNTO-1) )
#define NLMSG_HDRLEN	 ((int) NLMSG_ALIGN(sizeof(struct nlmsghdr)))
#define NLMSG_LENGTH(len) ((len)+NLMSG_ALIGN(NLMSG_HDRLEN))
#define NLMSG_SPACE(len) NLMSG_ALIGN(NLMSG_LENGTH(len))
#define NLMSG_DATA(nlh)  ((void*)(((char*)nlh) + NLMSG_LENGTH(0)))
#define NLMSG_NEXT(nlh,len)	 ((len) -= NLMSG_ALIGN((nlh)->nlmsg_len), \
				  (struct nlmsghdr*)(((char*)(nlh)) + NLMSG_ALIGN((nlh)->nlmsg_len)))
#define NLMSG_OK(nlh,len) ((len) >= (int)sizeof(struct nlmsghdr) && \
			   (nlh)->nlmsg_len >= sizeof(struct nlmsghdr) && \
			   (nlh)->nlmsg_len <= (len))
#define NLMSG_PAYLOAD(nlh,len) ((nlh)->nlmsg_len - NLMSG_SPACE((len)))

#define NLMSG_NOOP		0x1	/* Nothing.		*/
#define NLMSG_ERROR		0x2	/* Error		*/
#define NLMSG_DONE		0x3	/* End of a dump	*/
#define NLMSG_OVERRUN		0x4	/* Data lost		*/

#define NLMSG_MIN_TYPE		0x10	/* < 0x10: reserved control messages */

struct nlmsgerr
{
	int		error;
	struct nlmsghdr msg;
};

#define NETLINK_ADD_MEMBERSHIP	1
#define NETLINK_DROP_MEMBERSHIP	2
#define NETLINK_PKTINFO		3

struct nl_pktinfo
{
	__u32	group;
};

#define NET_MAJOR 36		/* Major 36 is reserved for networking 						*/

enum {
	NETLINK_UNCONNECTED = 0,
	NETLINK_CONNECTED,
};

/*
 *  <------- NLA_HDRLEN ------> <-- NLA_ALIGN(payload)-->
 * +---------------------+- - -+- - - - - - - - - -+- - -+
 * |        Header       | Pad |     Payload       | Pad |
 * |   (struct nlattr)   | ing |                   | ing |
 * +---------------------+- - -+- - - - - - - - - -+- - -+
 *  <-------------- nlattr->nla_len -------------->
 */

struct nlattr
{
	__u16           nla_len;
	__u16           nla_type;
};

/*
 * nla_type (16 bits)
 * +---+---+-------------------------------+
 * | N | O | Attribute Type                |
 * +---+---+-------------------------------+
 * N := Carries nested attributes
 * O := Payload stored in network byte order
 *
 * Note: The N and O flag are mutually exclusive.
 */
#define NLA_F_NESTED		(1 << 15)
#define NLA_F_NET_BYTEORDER	(1 << 14)
#define NLA_TYPE_MASK		~(NLA_F_NESTED | NLA_F_NET_BYTEORDER)

#define NLA_ALIGNTO		4
#define NLA_ALIGN(len)		(((len) + NLA_ALIGNTO - 1) & ~(NLA_ALIGNTO - 1))
#define NLA_HDRLEN		((int) NLA_ALIGN(sizeof(struct nlattr)))

#endif	/* __LINUX_NETLINK_H */
'>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 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649
#============================================================================
# This library is free software; you can redistribute it and/or
# modify it under the terms of version 2.1 of the GNU Lesser General Public
# License as published by the Free Software Foundation.
#
# This library 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 library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#============================================================================
# Copyright (C) 2006-2007 XenSource Ltd.
#============================================================================

import inspect
import os
import Queue
import sets
import string
import sys
import traceback
import threading
import time
import xmlrpclib

from xen.xend import XendDomain, XendDomainInfo, XendNode, XendDmesg
from xen.xend import XendLogging, XendTaskManager

from xen.xend.XendAPIVersion import *
from xen.xend.XendAuthSessions import instance as auth_manager
from xen.xend.XendError import *
from xen.xend.XendClient import ERROR_INVALID_DOMAIN
from xen.xend.XendLogging import log
from xen.xend.XendNetwork import XendNetwork
from xen.xend.XendTask import XendTask
from xen.xend.XendPIFMetrics import XendPIFMetrics
from xen.xend.XendVMMetrics import XendVMMetrics

from xen.xend.XendAPIConstants import *
from xen.util.xmlrpclib2 import stringify

from xen.util.blkif import blkdev_name_to_number


AUTH_NONE = 'none'
AUTH_PAM = 'pam'

argcounts = {}

# ------------------------------------------
# Utility Methods for Xen API Implementation
# ------------------------------------------

def xen_api_success(value):
    """Wraps a return value in XenAPI format."""
    if value is None:
        s = ''
    else:
        s = stringify(value)
    return {"Status": "Success", "Value": s}

def xen_api_success_void():
    """Return success, but caller expects no return value."""
    return xen_api_success("")

def xen_api_error(error):
    """Wraps an error value in XenAPI format."""
    if type(error) == tuple:
        error = list(error)
    if type(error) != list:
        error = [error]
    if len(error) == 0:
        error = ['INTERNAL_ERROR', 'Empty list given to xen_api_error']

    return { "Status": "Failure",
             "ErrorDescription": [str(x) for x in error] }


def xen_api_todo():
    """Temporary method to make sure we track down all the TODOs"""
    return {"Status": "Error", "ErrorDescription": XEND_ERROR_TODO}


def now():
    return xmlrpclib.DateTime(time.strftime("%Y%m%dT%H:%M:%S", time.gmtime()))


# ---------------------------------------------------
# Event dispatch
# ---------------------------------------------------

EVENT_QUEUE_LENGTH = 50
event_registrations = {}

def event_register(session, reg_classes):
    if session not in event_registrations:
        event_registrations[session] = {
            'classes' : sets.Set(),
            'queue'   : Queue.Queue(EVENT_QUEUE_LENGTH),
            'next-id' : 1
            }
    if not reg_classes:
        reg_classes = classes
    event_registrations[session]['classes'].union_update(reg_classes)


def event_unregister(session, unreg_classes):
    if session not in event_registrations:
        return

    if unreg_classes:
        event_registrations[session]['classes'].intersection_update(
            unreg_classes)
        if len(event_registrations[session]['classes']) == 0:
            del event_registrations[session]
    else:
        del event_registrations[session]


def event_next(session):
    if session not in event_registrations:
        return xen_api_error(['SESSION_NOT_REGISTERED', session])
    queue = event_registrations[session]['queue']
    events = [queue.get()]
    try:
        while True:
            events.append(queue.get(False))
    except Queue.Empty:
        pass

    return xen_api_success(events)


def _ctor_event_dispatch(xenapi, ctor, api_cls, session, args):
    result = ctor(xenapi, session, *args)
    if result['Status'] == 'Success':
        ref = result['Value']
        _event_dispatch('add', api_cls, ref, '')
    return result


def _dtor_event_dispatch(xenapi, dtor, api_cls, session, ref, args):
    result = dtor(xenapi, session, ref, *args)
    if result['Status'] == 'Success':
        _event_dispatch('del', api_cls, ref, '')
    return result


def _setter_event_dispatch(xenapi, setter, api_cls, attr_name, session, ref,
                           args):
    result = setter(xenapi, session, ref, *args)
    if result['Status'] == 'Success':
        _event_dispatch('mod', api_cls, ref, attr_name)
    return result


def _event_dispatch(operation, api_cls, ref, attr_name):
    event = {
        'timestamp' : now(),
        'class'     : api_cls,
        'operation' : operation,
        'ref'       : ref,
        'obj_uuid'  : ref,
        'field'     : attr_name,
        }
    for reg in event_registrations.values():
        if api_cls in reg['classes']:
            event['id'] = reg['next-id']
            reg['next-id'] += 1
            reg['queue'].put(event)


# ---------------------------------------------------
# Python Method Decorators for input value validation
# ---------------------------------------------------

def trace(func, api_name = ''):
    """Decorator to trace XMLRPC Xen API methods.

    @param func: function with any parameters
    @param api_name: name of the api call for debugging.
    """
    if hasattr(func, 'api'):
        api_name = func.api
    def trace_func(self, *args, **kwargs):
        log.debug('%s: %s' % (api_name, args))
        return func(self, *args, **kwargs)
    trace_func.api = api_name
    return trace_func


def catch_typeerror(func):
    """Decorator to catch any TypeErrors and translate them into Xen-API
    errors.

    @param func: function with params: (self, ...)
    @rtype: callable object
    """
    def f(self, *args, **kwargs):
        try:
            return func(self, *args, **kwargs)
        except TypeError, exn:
            #log.exception('catch_typeerror')
            if hasattr(func, 'api') and func.api in argcounts:
                # Assume that if the argument count was wrong and if the
                # exception was thrown inside this file, then it is due to an
                # invalid call from the client, otherwise it's an internal
                # error (which will be handled further up).
                expected = argcounts[func.api]
                actual = len(args) + len(kwargs)
                if expected != actual:
                    tb = sys.exc_info()[2]
                    try:
                        sourcefile = traceback.extract_tb(tb)[-1][0]
                        if sourcefile == inspect.getsourcefile(XendAPI):
                            return xen_api_error(
                                ['MESSAGE_PARAMETER_COUNT_MISMATCH',
                                 func.api, expected, actual])
                    finally:
                        del tb
            raise

    return f


def session_required(func):
    """Decorator to verify if session is valid before calling method.

    @param func: function with params: (self, session, ...)
    @rtype: callable object
    """    
    def check_session(self, session, *args, **kwargs):
        if auth_manager().is_session_valid(session):
            return func(self, session, *args, **kwargs)
        else:
            return xen_api_error(['SESSION_INVALID', session])

    return check_session


def _is_valid_ref(ref, validator):
    return type(ref) == str and validator(ref)

def _check_ref(validator, clas, func, api, session, ref, *args, **kwargs):
    if _is_valid_ref(ref, validator):
        return func(api, session, ref, *args, **kwargs)
    else:
        return xen_api_error(['HANDLE_INVALID', clas, ref])


def valid_host(func):
    """Decorator to verify if host_ref is valid before calling method.

    @param func: function with params: (self, session, host_ref, ...)
    @rtype: callable object
    """
    return lambda *args, **kwargs: \
           _check_ref(XendNode.instance().is_valid_host,
                      'host', func, *args, **kwargs)

def valid_host_metrics(func):
    """Decorator to verify if host_metrics_ref is valid before calling
    method.

    @param func: function with params: (self, session, host_metrics_ref)
    @rtype: callable object
    """
    return lambda *args, **kwargs: \
           _check_ref(lambda r: r == XendNode.instance().host_metrics_uuid,
                      'host_metrics', func, *args, **kwargs)

def valid_host_cpu(func):
    """Decorator to verify if host_cpu_ref is valid before calling method.

    @param func: function with params: (self, session, host_cpu_ref, ...)
    @rtype: callable object
    """    
    return lambda *args, **kwargs: \
           _check_ref(XendNode.instance().is_valid_cpu,
                      'host_cpu', func, *args, **kwargs)

def valid_vm(func):
    """Decorator to verify if vm_ref is valid before calling method.

    @param func: function with params: (self, session, vm_ref, ...)
    @rtype: callable object
    """    
    return lambda *args, **kwargs: \
           _check_ref(XendDomain.instance().is_valid_vm,
                      'VM', func, *args, **kwargs)

def valid_vm_metrics(func):
    """Decorator to verify if vm_metrics_ref is valid before calling method.

    @param func: function with params: (self, session, vm_metrics_ref, ...)
    @rtype: callable object
    """    
    return lambda *args, **kwargs: \
           _check_ref(XendVMMetrics.is_valid_vm_metrics,
                      'VM_metrics', func, *args, **kwargs)

def valid_network(func):
    """Decorator to verify if network_ref is valid before calling method.

    @param func: function with params: (self, session, network_ref, ...)
    @rtype: callable object
    """    
    return lambda *args, **kwargs: \
           _check_ref(XendNode.instance().is_valid_network,
                      'network', func, *args, **kwargs)

def valid_vbd(func):
    """Decorator to verify if vbd_ref is valid before calling method.

    @param func: function with params: (self, session, vbd_ref, ...)
    @rtype: callable object
    """    
    return lambda *args, **kwargs: \
           _check_ref(lambda r: XendDomain.instance().is_valid_dev('vbd', r),
                      'VBD', func, *args, **kwargs)

def valid_vbd_metrics(func):
    """Decorator to verify if ref is valid before calling method.

    @param func: function with params: (self, session, ref, ...)
    @rtype: callable object
    """    
    return lambda *args, **kwargs: \
           _check_ref(lambda r: XendDomain.instance().is_valid_dev('vbd', r),
                      'VBD_metrics', func, *args, **kwargs)

def valid_vif(func):
    """Decorator to verify if vif_ref is valid before calling method.

    @param func: function with params: (self, session, vif_ref, ...)
    @rtype: callable object
    """
    return lambda *args, **kwargs: \
           _check_ref(lambda r: XendDomain.instance().is_valid_dev('vif', r),
                      'VIF', func, *args, **kwargs)

def valid_vif_metrics(func):
    """Decorator to verify if ref is valid before calling method.

    @param func: function with params: (self, session, ref, ...)
    @rtype: callable object
    """    
    return lambda *args, **kwargs: \
           _check_ref(lambda r: XendDomain.instance().is_valid_dev('vif', r),
                      'VIF_metrics', func, *args, **kwargs)

def valid_vdi(func):
    """Decorator to verify if vdi_ref is valid before calling method.

    @param func: function with params: (self, session, vdi_ref, ...)
    @rtype: callable object
    """
    return lambda *args, **kwargs: \
           _check_ref(XendNode.instance().is_valid_vdi,
                      'VDI', func, *args, **kwargs)

def valid_vtpm(func):
    """Decorator to verify if vtpm_ref is valid before calling method.

    @param func: function with params: (self, session, vtpm_ref, ...)
    @rtype: callable object
    """
    return lambda *args, **kwargs: \
           _check_ref(lambda r: XendDomain.instance().is_valid_dev('vtpm', r),
                      'VTPM', func, *args, **kwargs)


def valid_console(func):
    """Decorator to verify if console_ref is valid before calling method.

    @param func: function with params: (self, session, console_ref, ...)
    @rtype: callable object
    """
    return lambda *args, **kwargs: \
           _check_ref(lambda r: XendDomain.instance().is_valid_dev('console',
                                                                   r),
                      'console', func, *args, **kwargs)

def valid_sr(func):
    """Decorator to verify if sr_ref is valid before calling method.

    @param func: function with params: (self, session, sr_ref, ...)
    @rtype: callable object
    """
    return lambda *args, **kwargs: \
           _check_ref(lambda r: XendNode.instance().is_valid_sr,
                      'SR', func, *args, **kwargs)

def valid_pif(func):
    """Decorator to verify if pif_ref is valid before calling
    method.

    @param func: function with params: (self, session, pif_ref)
    @rtype: callable object
    """
    return lambda *args, **kwargs: \
           _check_ref(lambda r: r in XendNode.instance().pifs,
                      'PIF', func, *args, **kwargs)

def valid_pif_metrics(func):
    """Decorator to verify if pif_metrics_ref is valid before calling
    method.

    @param func: function with params: (self, session, pif_metrics_ref)
    @rtype: callable object
    """
    return lambda *args, **kwargs: \
           _check_ref(lambda r: r in XendNode.instance().pif_metrics,
                      'PIF_metrics', func, *args, **kwargs)

def valid_task(func):
    """Decorator to verify if task_ref is valid before calling
    method.

    @param func: function with params: (self, session, task_ref)
    @rtype: callable object
    """
    return lambda *args, **kwargs: \
           _check_ref(XendTaskManager.get_task,
                      'task', func, *args, **kwargs)

def valid_debug(func):
    """Decorator to verify if task_ref is valid before calling
    method.

    @param func: function with params: (self, session, task_ref)
    @rtype: callable object
    """
    return lambda *args, **kwargs: \
           _check_ref(lambda r: r in XendAPI._debug,
                      'debug', func, *args, **kwargs)

# -----------------------------
# Bridge to Legacy XM API calls
# -----------------------------

def do_vm_func(fn_name, vm_ref, *args, **kwargs):
    """Helper wrapper func to abstract away from repetitive code.

    @param fn_name: function name for XendDomain instance
    @type fn_name: string
    @param vm_ref: vm_ref
    @type vm_ref: string
    @param *args: more arguments
    @type *args: tuple
    """
    try:
        xendom = XendDomain.instance()
        fn = getattr(xendom, fn_name)
        xendom.do_legacy_api_with_uuid(fn, vm_ref, *args, **kwargs)
        return xen_api_success_void()
    except VMBadState, exn:
        return xen_api_error(['VM_BAD_POWER_STATE', vm_ref, exn.expected,
                              exn.actual])


classes = {
    'session'      : None,
    'event'        : None,
    'host'         : valid_host,
    'host_cpu'     : valid_host_cpu,
    'host_metrics' : valid_host_metrics,
    'network'      : valid_network,
    'VM'           : valid_vm,
    'VM_metrics'   : valid_vm_metrics,
    'VBD'          : valid_vbd,
    'VBD_metrics'  : valid_vbd_metrics,
    'VIF'          : valid_vif,
    'VIF_metrics'  : valid_vif_metrics,
    'VDI'          : valid_vdi,
    'VTPM'         : valid_vtpm,
    'console'      : valid_console,
    'SR'           : valid_sr,
    'PIF'          : valid_pif,
    'PIF_metrics'  : valid_pif_metrics,
    'task'         : valid_task,
    'debug'        : valid_debug,
}

autoplug_classes = {
    'network'     : XendNetwork,
    'VM_metrics'  : XendVMMetrics,
    'PIF_metrics' : XendPIFMetrics,
}


class XendAPI(object):
    """Implementation of the Xen-API in Xend. Expects to be
    used via XMLRPCServer.

    All methods that need a valid session are marked with
    a L{session_required} decorator that will
    transparently perform the required session authentication.

    We need to support Python <2.4, so we use the old decorator syntax.

    All XMLRPC accessible methods require an 'api' attribute and
    is set to the XMLRPC function name which the method implements.
    """

    __decorated__ = False
    __init_lock__ = threading.Lock()
    _debug = {}
    
    def __new__(cls, *args, **kwds):
        """ Override __new__ to decorate the class only once.

        Lock to make sure the classes are not decorated twice.
        """
        cls.__init_lock__.acquire()
        try:
            if not cls.__decorated__:
                cls._decorate()
                cls.__decorated__ = True
                
            return object.__new__(cls, *args, **kwds)
        finally:
            cls.__init_lock__.release()
            
    def _decorate(cls):
        """ Decorate all the object methods to have validators
        and appropriate function attributes.

        This should only be executed once for the duration of the
        server.
        """
        global_validators = [session_required, catch_typeerror]


        # Cheat methods
        # -------------
        # Methods that have a trivial implementation for all classes.
        # 1. get_by_uuid == getting by ref, so just return uuid for
        #    all get_by_uuid() methods.
        
        for api_cls in classes.keys():
            if api_cls == 'session':
                continue
            
            get_by_uuid = '%s_get_by_uuid' % api_cls
            get_uuid = '%s_get_uuid' % api_cls
            def _get_by_uuid(_1, _2, ref):
                return xen_api_success(ref)

            def _get_uuid(_1, _2, ref):
                return xen_api_success(ref)

            setattr(cls, get_by_uuid, _get_by_uuid)
            setattr(cls, get_uuid,    _get_uuid)


        # Autoplugging classes
        # --------------------
        # These have all of their methods grabbed out from the implementation
        # class, and wrapped up to be compatible with the Xen-API.
        
        for api_cls, impl_cls in autoplug_classes.items():
            def doit(n):
                getter = getattr(cls, '_%s_get' % api_cls)
                dot_n = '%s.%s' % (api_cls, n)
                full_n = '%s_%s' % (api_cls, n)
                if not hasattr(cls, full_n):
                    f = getattr(impl_cls, n)
                    argcounts[dot_n] = f.func_code.co_argcount + 1
                    setattr(cls, full_n,
                            lambda s, session, ref, *args: \
                               xen_api_success( \
                                   f(getter(s, session, ref), *args)))

            ro_attrs = getattr(cls, '%s_attr_ro' % api_cls, [])
            rw_attrs = getattr(cls, '%s_attr_rw' % api_cls, [])
            methods  = getattr(cls, '%s_methods' % api_cls, [])
            funcs    = getattr(cls, '%s_funcs'   % api_cls, [])
            
            for attr_name in ro_attrs + rw_attrs:
                doit('get_%s' % attr_name)
            for attr_name in rw_attrs + cls.Base_attr_rw:
                doit('set_%s' % attr_name)
            for method_name, return_type in methods + cls.Base_methods:
                doit('%s' % method_name)
            for func_name, return_type in funcs + cls.Base_funcs:
                doit('%s' % func_name)


        def wrap_method(name, new_f):
            try:
                f = getattr(cls, name)
                wrapped_f = (lambda *args: new_f(f, *args))
                wrapped_f.api = f.api
                wrapped_f.async = f.async
                setattr(cls, name, wrapped_f)
            except AttributeError:
                # Logged below (API call: %s not found)
                pass


        def setter_event_wrapper(api_cls, attr_name):
            setter_name = '%s_set_%s' % (api_cls, attr_name)
            wrap_method(
                setter_name,
                lambda setter, s, session, ref, *args:
                _setter_event_dispatch(s, setter, api_cls, attr_name,
                                       session, ref, args))


        def ctor_event_wrapper(api_cls):
            ctor_name = '%s_create' % api_cls
            wrap_method(
                ctor_name,
                lambda ctor, s, session, *args:
                _ctor_event_dispatch(s, ctor, api_cls, session, args))


        def dtor_event_wrapper(api_cls):
            dtor_name = '%s_destroy' % api_cls
            wrap_method(
                dtor_name,
                lambda dtor, s, session, ref, *args:
                _dtor_event_dispatch(s, dtor, api_cls, session, ref, args))


        # Wrapping validators around XMLRPC calls
        # ---------------------------------------

        for api_cls, validator in classes.items():
            def doit(n, takes_instance, async_support = False,
                     return_type = None):
                n_ = n.replace('.', '_')
                try:
                    f = getattr(cls, n_)
                    if n not in argcounts:
                        argcounts[n] = f.func_code.co_argcount - 1
                    
                    validators = takes_instance and validator and \
                                 [validator] or []

                    validators += global_validators
                    for v in validators:
                        f = v(f)
                        f.api = n
                        f.async = async_support
                        if return_type:
                            f.return_type = return_type
                    
                    setattr(cls, n_, f)
                except AttributeError:
                    log.warn("API call: %s not found" % n)


            ro_attrs = getattr(cls, '%s_attr_ro' % api_cls, [])
            rw_attrs = getattr(cls, '%s_attr_rw' % api_cls, [])
            methods  = getattr(cls, '%s_methods' % api_cls, [])
            funcs    = getattr(cls, '%s_funcs'   % api_cls, [])

            # wrap validators around readable class attributes
            for attr_name in ro_attrs + rw_attrs + cls.Base_attr_ro:
                doit('%s.get_%s' % (api_cls, attr_name), True,
                     async_support = False)

            # wrap validators around writable class attrributes
            for attr_name in rw_attrs + cls.Base_attr_rw:
                doit('%s.set_%s' % (api_cls, attr_name), True,
                     async_support = False)
                setter_event_wrapper(api_cls, attr_name)

            # wrap validators around methods
            for method_name, return_type in methods + cls.Base_methods:
                doit('%s.%s' % (api_cls, method_name), True,
                     async_support = True)

            # wrap validators around class functions
            for func_name, return_type in funcs + cls.Base_funcs:
                doit('%s.%s' % (api_cls, func_name), False, async_support = True,
                     return_type = return_type)

            ctor_event_wrapper(api_cls)
            dtor_event_wrapper(api_cls)


    _decorate = classmethod(_decorate)

    def __init__(self, auth):
        self.auth = auth

    Base_attr_ro = ['uuid']
    Base_attr_rw = []
    Base_methods = [('get_record', 'Struct')]
    Base_funcs   = [('get_all', 'Set'), ('get_by_uuid', None)]

    # Xen API: Class Session
    # ----------------------------------------------------------------
    # NOTE: Left unwrapped by __init__

    session_attr_ro = ['this_host', 'this_user', 'last_active']
    session_methods = [('logout', None)]

    def session_get_all(self, session):
        return xen_api_success([session])

    def session_login_with_password(self, *args):
        if len(args) != 2:
            return xen_api_error(
                ['MESSAGE_PARAMETER_COUNT_MISMATCH',
                 'session.login_with_password', 2, len(args)])
        username = args[0]
        password = args[1]
        try:
            session = ((self.auth == AUTH_NONE and
                        auth_manager().login_unconditionally(username)) or
                       auth_manager().login_with_password(username, password))
            return xen_api_success(session)
        except XendError, e:
            return xen_api_error(['SESSION_AUTHENTICATION_FAILED'])
    session_login_with_password.api = 'session.login_with_password'

    # object methods
    def session_logout(self, session):
        auth_manager().logout(session)
        return xen_api_success_void()

    def session_get_record(self, session, self_session):
        if self_session != session:
            return xen_api_error(['PERMISSION_DENIED'])
        record = {'uuid'       : session,
                  'this_host'  : XendNode.instance().uuid,
                  'this_user'  : auth_manager().get_user(session),
                  'last_active': now()}
        return xen_api_success(record)

    def session_get_uuid(self, session, self_session):
        return xen_api_success(self_session)

    def session_get_by_uuid(self, session, self_session):
        return xen_api_success(self_session)

    # attributes (ro)
    def session_get_this_host(self, session, self_session):
        if self_session != session:
            return xen_api_error(['PERMISSION_DENIED'])
        return xen_api_success(XendNode.instance().uuid)

    def session_get_this_user(self, session, self_session):
        if self_session != session:
            return xen_api_error(['PERMISSION_DENIED'])
        user = auth_manager().get_user(session)
        if user is not None:
            return xen_api_success(user)
        return xen_api_error(['SESSION_INVALID', session])

    def session_get_last_active(self, session, self_session):
        if self_session != session:
            return xen_api_error(['PERMISSION_DENIED'])
        return xen_api_success(now())


    # Xen API: Class User
    # ----------------------------------------------------------------
    # TODO: NOT IMPLEMENTED YET

    # Xen API: Class Tasks
    # ----------------------------------------------------------------

    task_attr_ro = ['name_label',
                    'name_description',
                    'status',
                    'progress',
                    'type',
                    'result',
                    'error_code',
                    'error_info',
                    'allowed_operations',
                    'session'
                    ]

    task_attr_rw = []

    task_funcs = [('get_by_name_label', 'Set(task)'),
                  ('cancel', None)]

    def task_get_name_label(self, session, task_ref):
        task = XendTaskManager.get_task(task_ref)
        return xen_api_success(task.name_label)

    def task_get_name_description(self, session, task_ref):
        task = XendTaskManager.get_task(task_ref)
        return xen_api_success(task.name_description)

    def task_get_status(self, session, task_ref):
        task = XendTaskManager.get_task(task_ref)
        return xen_api_success(task.get_status())

    def task_get_progress(self, session, task_ref):
        task = XendTaskManager.get_task(task_ref)
        return xen_api_success(task.progress)

    def task_get_type(self, session, task_ref):
        task = XendTaskManager.get_task(task_ref)
        return xen_api_success(task.type)

    def task_get_result(self, session, task_ref):
        task = XendTaskManager.get_task(task_ref)
        return xen_api_success(task.result)

    def task_get_error_code(self, session, task_ref):
        task = XendTaskManager.get_task(task_ref)
        return xen_api_success(task.error_code)

    def task_get_error_info(self, session, task_ref):
        task = XendTaskManager.get_task(task_ref)
        return xen_api_success(task.error_info)

    def task_get_allowed_operations(self, session, task_ref):
        return xen_api_success({})

    def task_get_session(self, session, task_ref):
        task = XendTaskManager.get_task(task_ref)
        return xen_api_success(task.session)

    def task_get_all(self, session):
        tasks = XendTaskManager.get_all_tasks()
        return xen_api_success(tasks)

    def task_get_record(self, session, task_ref):
        task = XendTaskManager.get_task(task_ref)
        return xen_api_success(task.get_record())

    def task_cancel(self, session, task_ref):
        return xen_api_error('OPERATION_NOT_ALLOWED')

    def task_get_by_name_label(self, session, name):
        return xen_api_success(XendTaskManager.get_task_by_name(name))

    # Xen API: Class host
    # ----------------------------------------------------------------    

    host_attr_ro = ['software_version',
                    'resident_VMs',
                    'PIFs',
                    'host_CPUs',
                    'cpu_configuration',
                    'metrics',
                    'capabilities',
                    'supported_bootloaders',
                    'API_version_major',
                    'API_version_minor',
                    'API_version_vendor',
                    'API_version_vendor_implementation']
    
    host_attr_rw = ['name_label',
                    'sched_policy',
                    'name_description',
                    'other_config']

    host_methods = [('disable', None),
                    ('enable', None),
                    ('reboot', None),
                    ('shutdown', None),
                    ('add_to_other_config', None),
                    ('remove_from_other_config', None),
                    ('dmesg', 'String'),
                    ('dmesg_clear', 'String'),
                    ('get_log', 'String'),
                    ('send_debug_keys', None)]
    
    host_funcs = [('get_by_name_label', 'Set(host)')]

    # attributes
    def host_get_name_label(self, session, host_ref):
        return xen_api_success(XendNode.instance().name)
    def host_set_name_label(self, session, host_ref, new_name):
        XendNode.instance().set_name(new_name)
        return xen_api_success_void()
    def host_get_name_description(self, session, host_ref):
        return xen_api_success(XendNode.instance().description)
    def host_set_name_description(self, session, host_ref, new_desc):
        XendNode.instance().set_description(new_desc)
        return xen_api_success_void()
    def host_get_other_config(self, session, host_ref):
        return xen_api_success(XendNode.instance().other_config)
    def host_set_other_config(self, session, host_ref, other_config):
        node = XendNode.instance()
        node.other_config = dict(other_config)
        node.save()
        return xen_api_success_void()
    def host_add_to_other_config(self, session, host_ref, key, value):
        node = XendNode.instance()
        node.other_config[key] = value
        node.save()
        return xen_api_success_void()
    def host_remove_from_other_config(self, session, host_ref, key):
        node = XendNode.instance()
        if key in node.other_config:
            del node.other_config[key]
            node.save()
        return xen_api_success_void()
    def host_get_API_version_major(self, _, ref):
        return xen_api_success(XEN_API_VERSION_MAJOR)
    def host_get_API_version_minor(self, _, ref):
        return xen_api_success(XEN_API_VERSION_MINOR)
    def host_get_API_version_vendor(self, _, ref):
        return xen_api_success(XEN_API_VERSION_VENDOR)
    def host_get_API_version_vendor_implementation(self, _, ref):
        return xen_api_success(XEN_API_VERSION_VENDOR_IMPLEMENTATION)
    def host_get_software_version(self, session, host_ref):
        return xen_api_success(XendNode.instance().xen_version())
    def host_get_resident_VMs(self, session, host_ref):
        return xen_api_success(XendDomain.instance().get_domain_refs())
    def host_get_PIFs(self, session, ref):
        return xen_api_success(XendNode.instance().get_PIF_refs())
    def host_get_host_CPUs(self, session, host_ref):
        return xen_api_success(XendNode.instance().get_host_cpu_refs())
    def host_get_metrics(self, _, ref):
        return xen_api_success(XendNode.instance().host_metrics_uuid)
    def host_get_capabilities(self, session, host_ref):
        return xen_api_success(XendNode.instance().get_capabilities())
    def host_get_supported_bootloaders(self, session, host_ref):
        return xen_api_success(['pygrub'])
    def host_get_sched_policy(self, _, host_ref):
        return xen_api_success(XendNode.instance().get_vcpus_policy())
    def host_set_sched_policy(self, _, host_ref, policy):
        return xen_api_todo()
    def host_get_cpu_configuration(self, _, host_ref):
        return xen_api_success(XendNode.instance().get_cpu_configuration())
    
    # object methods
    def host_disable(self, session, host_ref):
        XendDomain.instance().set_allow_new_domains(False)
        return xen_api_success_void()
    def host_enable(self, session, host_ref):
        XendDomain.instance().set_allow_new_domains(True)
        return xen_api_success_void()
    def host_reboot(self, session, host_ref):
        if not XendDomain.instance().allow_new_domains():
            return xen_api_error(XEND_ERROR_HOST_RUNNING)
        return xen_api_error(XEND_ERROR_UNSUPPORTED)
    def host_shutdown(self, session, host_ref):
        if not XendDomain.instance().allow_new_domains():
            return xen_api_error(XEND_ERROR_HOST_RUNNING)
        return xen_api_error(XEND_ERROR_UNSUPPORTED)        

    def host_dmesg(self, session, host_ref):
        return xen_api_success(XendDmesg.instance().info())

    def host_dmesg_clear(self, session, host_ref):
        return xen_api_success(XendDmesg.instance().clear())

    def host_get_log(self, session, host_ref):
        log_file = open(XendLogging.getLogFilename())
        log_buffer = log_file.read()
        return xen_api_success(log_buffer)

    def host_send_debug_keys(self, _, host_ref, keys):
        node = XendNode.instance()
        node.send_debug_keys(keys)
        return xen_api_success_void()

    def host_get_record(self, session, host_ref):
        node = XendNode.instance()
        dom = XendDomain.instance()
        record = {'uuid': node.uuid,
                  'name_label': node.name,
                  'name_description': '',
                  'API_version_major': XEN_API_VERSION_MAJOR,
                  'API_version_minor': XEN_API_VERSION_MINOR,
                  'API_version_vendor': XEN_API_VERSION_VENDOR,
                  'API_version_vendor_implementation':
                  XEN_API_VERSION_VENDOR_IMPLEMENTATION,
                  'software_version': node.xen_version(),
                  'other_config': node.other_config,
                  'resident_VMs': dom.get_domain_refs(),
                  'host_CPUs': node.get_host_cpu_refs(),
                  'cpu_configuration': node.get_cpu_configuration(),
                  'metrics': node.host_metrics_uuid,
                  'capabilities': node.get_capabilities(),
                  'supported_bootloaders': 'pygrub',
                  'sched_policy': node.get_vcpus_policy()}
        return xen_api_success(record)

    # class methods
    def host_get_all(self, session):
        return xen_api_success((XendNode.instance().uuid,))
    def host_get_by_name_label(self, session, name):
        if XendNode.instance().name == name:
            return xen_api_success((XendNode.instance().uuid,))
        return xen_api_success([])
    

    # Xen API: Class host_CPU
    # ----------------------------------------------------------------

    host_cpu_attr_ro = ['host',
                        'number',
                        'vendor',
                        'speed',
                        'modelname',
                        'stepping',
                        'flags',
                        'utilisation',
                        'features']

    # attributes
    def _host_cpu_get(self, ref, field):
        return xen_api_success(
            XendNode.instance().get_host_cpu_field(ref, field))

    def host_cpu_get_host(self, _, ref):
        return xen_api_success(XendNode.instance().uuid)
    def host_cpu_get_features(self, _, ref):
        return self._host_cpu_get(ref, 'features')
    def host_cpu_get_number(self, _, ref):
        return self._host_cpu_get(ref, 'number')
    def host_cpu_get_vendor(self, _, ref):
        return self._host_cpu_get(ref, 'vendor')
    def host_cpu_get_speed(self, _, ref):
        return self._host_cpu_get(ref, 'speed')
    def host_cpu_get_modelname(self, _, ref):
        return self._host_cpu_get(ref, 'modelname')
    def host_cpu_get_stepping(self, _, ref):
        return self._host_cpu_get(ref, 'stepping')
    def host_cpu_get_flags(self, _, ref):
        return self._host_cpu_get(ref, 'flags')
    def host_cpu_get_utilisation(self, _, ref):
        return xen_api_success(XendNode.instance().get_host_cpu_load(ref))

    # object methods
    def host_cpu_get_record(self, _, ref):
        node = XendNode.instance()
        record = dict([(f, node.get_host_cpu_field(ref, f))
                       for f in self.host_cpu_attr_ro
                       if f not in ['uuid', 'host', 'utilisation']])
        record['uuid'] = ref
        record['host'] = node.uuid
        record['utilisation'] = node.get_host_cpu_load(ref)
        return xen_api_success(record)

    # class methods
    def host_cpu_get_all(self, session):
        return xen_api_success(XendNode.instance().get_host_cpu_refs())


    # Xen API: Class host_metrics
    # ----------------------------------------------------------------

    host_metrics_attr_ro = ['memory_total',
                            'memory_free',
                            'last_updated']
    host_metrics_attr_rw = []
    host_metrics_methods = []

    def host_metrics_get_all(self, _):
        return xen_api_success([XendNode.instance().host_metrics_uuid])

    def _host_metrics_get(self, ref, f):
        return xen_api_success(getattr(node, f)())

    def host_metrics_get_record(self, _, ref):
        return xen_api_success({
            'uuid'         : ref,
            'memory_total' : self._host_metrics_get_memory_total(),
            'memory_free'  : self._host_metrics_get_memory_free(),
            'last_updated' : now(),
            })

    def host_metrics_get_memory_total(self, _1, _2):
        return xen_api_success(self._host_metrics_get_memory_total())

    def host_metrics_get_memory_free(self, _1, _2):
        return xen_api_success(self._host_metrics_get_memory_free())

    def host_metrics_get_last_updated(self, _1, _2):
        return xen_api_success(now())

    def _host_metrics_get_memory_total(self):
        node = XendNode.instance()
        return node.xc.physinfo()['total_memory'] * 1024

    def _host_metrics_get_memory_free(self):
        node = XendNode.instance()
        return node.xc.physinfo()['free_memory'] * 1024


    # Xen API: Class network
    # ----------------------------------------------------------------

    network_attr_ro = ['VIFs', 'PIFs']
    network_attr_rw = ['name_label',
                       'name_description',
                       'other_config']
    network_methods = [('add_to_other_config', None),
                       ('remove_from_other_config', None),
                       ('destroy', None)]
    network_funcs = [('create', None)]
    
    def _network_get(self, _, ref):
        return XendNode.instance().get_network(ref)

    def network_get_all(self, _):
        return xen_api_success(XendNode.instance().get_network_refs())

    def network_create(self, _, record):
        return xen_api_success(XendNode.instance().network_create(record))

    def network_destroy(self, _, ref):
        return xen_api_success(XendNode.instance().network_destroy(ref))


    # Xen API: Class PIF
    # ----------------------------------------------------------------

    PIF_attr_ro = ['network',
                   'host',
                   'metrics']
    PIF_attr_rw = ['device',
                   'MAC',
                   'MTU',
                   'VLAN']

    PIF_attr_inst = PIF_attr_rw

    PIF_methods = [('create_VLAN', 'int'), ('destroy', None)]

    def _get_PIF(self, ref):
        return XendNode.instance().pifs[ref]

    def PIF_destroy(self, _, ref):
        try:
            return xen_api_success(XendNode.instance().PIF_destroy(ref))
        except PIFIsPhysical, exn:
            return xen_api_error(['PIF_IS_PHYSICAL', ref])

    # object methods
    def PIF_get_record(self, _, ref):
        return xen_api_success(self._get_PIF(ref).get_record())

    def PIF_get_all(self, _):
        return xen_api_success(XendNode.instance().pifs.keys())

    def PIF_get_metrics(self, _, ref):
        return xen_api_success(self._get_PIF(ref).metrics.uuid)

    def PIF_get_device(self, _, ref):
        return xen_api_success(self._get_PIF(ref).device)

    def PIF_get_network(self, _, ref):
        return xen_api_success(self._get_PIF(ref).network.uuid)

    def PIF_get_host(self, _, ref):
        return xen_api_success(self._get_PIF(ref).host.uuid)

    def PIF_get_MAC(self, _, ref):
        return xen_api_success(self._get_PIF(ref).mac)

    def PIF_get_MTU(self, _, ref):
        return xen_api_success(self._get_PIF(ref).mtu)

    def PIF_get_VLAN(self, _, ref):
        return xen_api_success(self._get_PIF(ref).vlan)

    def PIF_set_device(self, _, ref, device):
        return xen_api_success(self._get_PIF(ref).set_device(device))

    def PIF_set_MAC(self, _, ref, mac):
        return xen_api_success(self._get_PIF(ref).set_mac(mac))

    def PIF_set_MTU(self, _, ref, mtu):
        return xen_api_success(self._get_PIF(ref).set_mtu(mtu))

    def PIF_create_VLAN(self, _, ref, network, vlan):
        try:
            vlan = int(vlan)
        except:
            return xen_api_error(['VLAN_TAG_INVALID', vlan])

        try:
            node = XendNode.instance()
            
            if _is_valid_ref(network, node.is_valid_network):
                return xen_api_success(
                    node.PIF_create_VLAN(ref, network, vlan))
            else:
                return xen_api_error(['HANDLE_INVALID', 'network', network])
        except NetworkAlreadyConnected, exn:
            return xen_api_error(['NETWORK_ALREADY_CONNECTED',
                                  network, exn.pif_uuid])
        except VLANTagInvalid:
            return xen_api_error(['VLAN_TAG_INVALID', vlan])


    # Xen API: Class PIF_metrics
    # ----------------------------------------------------------------

    PIF_metrics_attr_ro = ['io_read_kbs',
                           'io_write_kbs',
                           'last_updated']
    PIF_metrics_attr_rw = []
    PIF_metrics_methods = []

    def PIF_metrics_get_all(self, _):
        return xen_api_success(XendNode.instance().pif_metrics.keys())

    def _PIF_metrics_get(self, _, ref):
        return XendNode.instance().pif_metrics[ref]


    # Xen API: Class VM
    # ----------------------------------------------------------------        

    VM_attr_ro = ['power_state',
                  'resident_on',
                  'consoles',
                  'VIFs',
                  'VBDs',
                  'VTPMs',
                  'tools_version',
                  'domid',
                  'is_control_domain',
                  'metrics'
                  ]
                  
    VM_attr_rw = ['name_label',
                  'name_description',
                  'user_version',
                  'is_a_template',
                  'auto_power_on',
                  'memory_dynamic_max',
                  'memory_dynamic_min',
                  'memory_static_max',
                  'memory_static_min',
                  'VCPUs_max',
                  'VCPUs_at_startup',
                  'VCPUs_params',
                  'actions_after_shutdown',
                  'actions_after_reboot',
                  'actions_after_suspend',
                  'actions_after_crash',
                  'PV_bootloader',
                  'PV_kernel',
                  'PV_ramdisk',
                  'PV_args',
                  'PV_bootloader_args',
                  'HVM_boot_policy',
                  'HVM_boot_params',
                  'platform',
                  'PCI_bus',
                  'other_config']

    VM_methods = [('clone', 'VM'),
                  ('start', None),
                  ('pause', None),
                  ('unpause', None),
                  ('clean_shutdown', None),
                  ('clean_reboot', None),
                  ('hard_shutdown', None),
                  ('hard_reboot', None),
                  ('suspend', None),
                  ('resume', None),
                  ('send_sysrq', None),
                  ('set_VCPUs_number_live', None),
                  ('add_to_HVM_boot_params', None),
                  ('remove_from_HVM_boot_params', None),
                  ('add_to_VCPUs_params', None),
                  ('add_to_VCPUs_params_live', None),
                  ('remove_from_VCPUs_params', None),
                  ('add_to_platform', None),
                  ('remove_from_platform', None),
                  ('add_to_other_config', None),
                  ('remove_from_other_config', None),
                  ('save', None),
                  ('set_memory_dynamic_max_live', None),
                  ('set_memory_dynamic_min_live', None),
                  ('send_trigger', None),
                  ('destroy', None)]
    
    VM_funcs  = [('create', 'VM'),
                 ('restore', None),
                 ('get_by_name_label', 'Set(VM)')]

    # parameters required for _create()
    VM_attr_inst = [
        'name_label',
        'name_description',
        'user_version',
        'is_a_template',
        'memory_static_max',
        'memory_dynamic_max',
        'memory_dynamic_min',
        'memory_static_min',
        'VCPUs_max',
        'VCPUs_at_startup',
        'VCPUs_params',
        'actions_after_shutdown',
        'actions_after_reboot',
        'actions_after_suspend',
        'actions_after_crash',
        'PV_bootloader',
        'PV_kernel',
        'PV_ramdisk',
        'PV_args',
        'PV_bootloader_args',
        'HVM_boot_policy',
        'HVM_boot_params',
        'platform',
        'PCI_bus',
        'other_config']
        
    def VM_get(self, name, session, vm_ref):
        return xen_api_success(
            XendDomain.instance().get_vm_by_uuid(vm_ref).info[name])

    def VM_set(self, name, session, vm_ref, value):
        xd = XendDomain.instance()
        dominfo = xd.get_vm_by_uuid(vm_ref)
        dominfo.info[name] = value
        return self._VM_save(dominfo)

    def _VM_save(self, dominfo):
        XendDomain.instance().managed_config_save(dominfo)
        return xen_api_success_void()

    # attributes (ro)
    def VM_get_power_state(self, session, vm_ref):
        dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
        return xen_api_success(dom.get_power_state())
    
    def VM_get_resident_on(self, session, vm_ref):
        return xen_api_success(XendNode.instance().uuid)
       
    def VM_get_memory_static_max(self, session, vm_ref):
        dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
        return xen_api_success(dom.get_memory_static_max())
    
    def VM_get_memory_static_min(self, session, vm_ref):
        dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
        return xen_api_success(dom.get_memory_static_min())
    
    def VM_get_VIFs(self, session, vm_ref):
        dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
        return xen_api_success(dom.get_vifs())
    
    def VM_get_VBDs(self, session, vm_ref):
        dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
        return xen_api_success(dom.get_vbds())
    
    def VM_get_VTPMs(self, session, vm_ref):
        dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
        return xen_api_success(dom.get_vtpms())

    def VM_get_consoles(self, session, vm_ref):
        dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
        return xen_api_success(dom.get_consoles())
    
    def VM_get_tools_version(self, session, vm_ref):
        dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
        return dom.get_tools_version()

    def VM_get_metrics(self, _, vm_ref):
        dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
        return xen_api_success(dom.get_metrics())

    def VM_get_VCPUs_max(self, _, vm_ref):
        dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
        return xen_api_todo()

    def VM_get_VCPUs_at_startup(self, _, vm_ref):
        dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
        return xen_api_todo()

    # attributes (rw)
    def VM_get_name_label(self, session, vm_ref):
        dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
        return xen_api_success(dom.getName())
    
    def VM_get_name_description(self, session, vm_ref):
        dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
        return xen_api_todo()
    
    def VM_get_user_version(self, session, vm_ref):
        dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
        return xen_api_todo()
    
    def VM_get_is_a_template(self, session, ref):
        return self.VM_get('is_a_template', session, ref)
    
    def VM_get_memory_dynamic_max(self, session, vm_ref):
        dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
        return xen_api_success(dom.get_memory_dynamic_max())

    def VM_get_memory_dynamic_min(self, session, vm_ref):
        dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
        return xen_api_success(dom.get_memory_dynamic_min())
    
    def VM_get_VCPUs_params(self, session, vm_ref):
        dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
        return xen_api_success(dom.get_vcpus_params())
    
    def VM_get_actions_after_shutdown(self, session, vm_ref):
        dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
        return xen_api_success(dom.get_on_shutdown())
    
    def VM_get_actions_after_reboot(self, session, vm_ref):
        dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
        return xen_api_success(dom.get_on_reboot())
    
    def VM_get_actions_after_suspend(self, session, vm_ref):
        dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
        return xen_api_success(dom.get_on_suspend())        
    
    def VM_get_actions_after_crash(self, session, vm_ref):
        dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
        return xen_api_success(dom.get_on_crash())
    
    def VM_get_PV_bootloader(self, session, vm_ref):
        return self.VM_get('PV_bootloader', session, vm_ref)
    
    def VM_get_PV_kernel(self, session, vm_ref):
        return self.VM_get('PV_kernel', session, vm_ref)
    
    def VM_get_PV_ramdisk(self, session, vm_ref):
        return self.VM_get('PV_ramdisk', session, vm_ref)
    
    def VM_get_PV_args(self, session, vm_ref):
        return self.VM_get('PV_args', session, vm_ref)

    def VM_get_PV_bootloader_args(self, session, vm_ref):
        return self.VM_get('PV_bootloader_args', session, vm_ref)

    def VM_get_HVM_boot_policy(self, session, vm_ref):
        return self.VM_get('HVM_boot_policy', session, vm_ref)
    
    def VM_get_HVM_boot_params(self, session, vm_ref):
        return self.VM_get('HVM_boot_params', session, vm_ref)
    
    def VM_get_platform(self, session, vm_ref):
        dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
        return xen_api_success(dom.get_platform())
    
    def VM_get_PCI_bus(self, session, vm_ref):
        dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
        return dom.get_pci_bus()
    
    def VM_set_PCI_bus(self, session, vm_ref, val):
        return self.VM_set('PCI_bus', session, vm_ref, val)
    
    def VM_get_other_config(self, session, vm_ref):
        return self.VM_get('other_config', session, vm_ref)        

    def VM_get_domid(self, _, ref):
        domid = XendDomain.instance().get_vm_by_uuid(ref).getDomid()
        return xen_api_success(domid is None and -1 or domid)

    def VM_get_is_control_domain(self, session, vm_ref):
        xd = XendDomain.instance()
        return xen_api_success(
            xd.get_vm_by_uuid(vm_ref) == xd.privilegedDomain())

    def VM_set_name_label(self, session, vm_ref, label):
        dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
        dom.setName(label)
        return self._VM_save(dom)
    
    def VM_set_name_description(self, session, vm_ref, desc):
        dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
        return xen_api_todo()
    
    def VM_set_user_version(self, session, vm_ref, ver):
        dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
        return xen_api_todo()
    
    def VM_set_is_a_template(self, session, vm_ref, is_template):
        dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
        return xen_api_todo()
    
    def VM_set_memory_dynamic_max(self, session, vm_ref, mem):
        dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
        dom.set_memory_dynamic_max(int(mem))
        return xen_api_success_void()

    def VM_set_memory_dynamic_min(self, session, vm_ref, mem):
        dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
        dom.set_memory_dynamic_min(int(mem))
        return xen_api_success_void()

    def VM_set_memory_static_max(self, session, vm_ref, mem):
        dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
        dom.set_memory_static_max(int(mem))
        return xen_api_success_void()
    
    def VM_set_memory_static_min(self, session, vm_ref, mem):
        dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
        dom.set_memory_static_min(int(mem))
        return xen_api_success_void()

    def VM_set_memory_dynamic_max_live(self, session, vm_ref, mem):
        dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
        dom.set_memory_dynamic_max(int(mem))
        # need to pass target as MiB
        dom.setMemoryTarget(int(mem)/1024/1024)
        return xen_api_success_void()

    def VM_set_memory_dynamic_min_live(self, session, vm_ref, mem):
        dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
        dom.set_memory_dynamic_min(int(mem))
        # need to pass target as MiB
        dom.setMemoryTarget(int(mem)/1024/1024)
        return xen_api_success_void()

    def VM_set_VCPUs_params(self, session, vm_ref, value):
        return self.VM_set('vcpus_params', session, vm_ref, value)

    def VM_add_to_VCPUs_params(self, session, vm_ref, key, value):
        dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
        if 'vcpus_params' not in dom.info:
            dom.info['vcpus_params'] = {}
        dom.info['vcpus_params'][key] = value
        return self._VM_save(dom)

    def VM_add_to_VCPUs_params_live(self, session, vm_ref, key, value):
        self.VM_add_to_VCPUs_params(session, vm_ref, key, value)
        self._VM_VCPUs_params_refresh(vm_ref)
        return xen_api_success_void()

    def _VM_VCPUs_params_refresh(self, vm_ref):
        xendom  = XendDomain.instance()
        xeninfo = xendom.get_vm_by_uuid(vm_ref)

        #update the cpumaps
        for key, value in xeninfo.info['vcpus_params'].items():
            if key.startswith("cpumap"):
                vcpu = int(key[6:])
                try:
                    cpus = map(int, value.split(","))
                    xendom.domain_pincpu(xeninfo.getDomid(), vcpu, cpus)
                except Exception, ex:
                    log.exception(ex)

        #need to update sched params aswell
        if 'weight' in xeninfo.info['vcpus_params'] \
           and 'cap' in xeninfo.info['vcpus_params']:
            weight = xeninfo.info['vcpus_params']['weight']
            cap = xeninfo.info['vcpus_params']['cap']
            xendom.domain_sched_credit_set(xeninfo.getDomid(), weight, cap)

    def VM_set_VCPUs_number_live(self, _, vm_ref, num):
        dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
        dom.setVCpuCount(int(num))
        return xen_api_success_void()
     
    def VM_remove_from_VCPUs_params(self, session, vm_ref, key):
        dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
        if 'vcpus_params' in dom.info \
               and key in dom.info['vcpus_params']:
            del dom.info['vcpus_params'][key]
            return self._VM_save(dom)
        else:
            return xen_api_success_void()
    
    def VM_set_actions_after_shutdown(self, session, vm_ref, action):
        if action not in XEN_API_ON_NORMAL_EXIT:
            return xen_api_error(['VM_ON_NORMAL_EXIT_INVALID', vm_ref])
        return self.VM_set('actions_after_shutdown', session, vm_ref, action)
    
    def VM_set_actions_after_reboot(self, session, vm_ref, action):
        if action not in XEN_API_ON_NORMAL_EXIT:
            return xen_api_error(['VM_ON_NORMAL_EXIT_INVALID', vm_ref])
        return self.VM_set('actions_after_reboot', session, vm_ref, action)
    
    def VM_set_actions_after_suspend(self, session, vm_ref, action):
        if action not in XEN_API_ON_NORMAL_EXIT:
            return xen_api_error(['VM_ON_NORMAL_EXIT_INVALID', vm_ref])
        return self.VM_set('actions_after_suspend', session, vm_ref, action)
    
    def VM_set_actions_after_crash(self, session, vm_ref, action):
        if action not in XEN_API_ON_CRASH_BEHAVIOUR:
            return xen_api_error(['VM_ON_CRASH_BEHAVIOUR_INVALID', vm_ref])
        return self.VM_set('actions_after_crash', session, vm_ref, action)

    def VM_set_HVM_boot_policy(self, session, vm_ref, value):
        if value != "" and value != "BIOS order":
            return xen_api_error(
                ['VALUE_NOT_SUPPORTED', 'VM.HVM_boot_policy', value,
                 'Xend supports only the "BIOS order" boot policy.'])
        else:
            return self.VM_set('HVM_boot_policy', session, vm_ref, value)

    def VM_set_HVM_boot_params(self, session, vm_ref, value):
        return self.VM_set('HVM_boot_params', session, vm_ref, value)

    def VM_add_to_HVM_boot_params(self, session, vm_ref, key, value):
        dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
        if 'HVM_boot_params' not in dom.info:
            dom.info['HVM_boot_params'] = {}
        dom.info['HVM_boot_params'][key] = value
        return self._VM_save(dom)

    def VM_remove_from_HVM_boot_params(self, session, vm_ref, key):
        dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
        if 'HVM_boot_params' in dom.info \
               and key in dom.info['HVM_boot_params']:
            del dom.info['HVM_boot_params'][key]
            return self._VM_save(dom)
        else:
            return xen_api_success_void()

    def VM_set_PV_bootloader(self, session, vm_ref, value):
        return self.VM_set('PV_bootloader', session, vm_ref, value)

    def VM_set_PV_kernel(self, session, vm_ref, value):
        return self.VM_set('PV_kernel', session, vm_ref, value)

    def VM_set_PV_ramdisk(self, session, vm_ref, value):
        return self.VM_set('PV_ramdisk', session, vm_ref, value)

    def VM_set_PV_args(self, session, vm_ref, value):
        return self.VM_set('PV_args', session, vm_ref, value)

    def VM_set_PV_bootloader_args(self, session, vm_ref, value):
        return self.VM_set('PV_bootloader_args', session, vm_ref, value)

    def VM_set_platform(self, session, vm_ref, value):
        return self.VM_set('platform', session, vm_ref, value)
    
    def VM_add_to_platform(self, session, vm_ref, key, value):
        dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
        plat = dom.get_platform()
        plat[key] = value
        return self.VM_set_platform(session, vm_ref, plat)

    def VM_remove_from_platform(self, session, vm_ref, key):
        dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
        plat = dom.get_platform()
        if key in plat:
            del plat[key]
            return self.VM_set_platform(session, vm_ref, plat)
        else:
            return xen_api_success_void()

    def VM_set_other_config(self, session, vm_ref, value):
        return self.VM_set('other_config', session, vm_ref, value)

    def VM_add_to_other_config(self, session, vm_ref, key, value):
        dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
        if dom and 'other_config' in dom.info:
            dom.info['other_config'][key] = value
        return self._VM_save(dom)

    def VM_remove_from_other_config(self, session, vm_ref, key):
        dom = XendDomain.instance().get_vm_by_uuid(vm_ref)
        if dom and 'other_config' in dom.info \
               and key in dom.info['other_config']:
            del dom.info['other_config'][key]
            return self._VM_save(dom)
        else:
            return xen_api_success_void()

    # class methods
    def VM_get_all(self, session):
        refs = [d.get_uuid() for d in XendDomain.instance().list('all')]
        return xen_api_success(refs)
    
    def VM_get_by_name_label(self, session, label):
        xendom = XendDomain.instance()
        dom = xendom.domain_lookup_nr(label)
        if dom:
            return xen_api_success([dom.get_uuid()])
        return xen_api_success([])
    
    def VM_create(self, session, vm_struct):
        xendom = XendDomain.instance()
        domuuid = XendTask.log_progress(0, 100,
                                        xendom.create_domain, vm_struct)
        return xen_api_success(domuuid)
    
    # object methods
    def VM_get_record(self, session, vm_ref):
        xendom = XendDomain.instance()
        xeninfo = xendom.get_vm_by_uuid(vm_ref)
        if not xeninfo:
            return xen_api_error(['HANDLE_INVALID', 'VM', vm_ref])

        domid = xeninfo.getDomid()

        record = {
            'uuid': xeninfo.get_uuid(),
            'power_state': xeninfo.get_power_state(),
            'name_label': xeninfo.getName(),
            'name_description': xeninfo.getName(),
            'user_version': 1,
            'is_a_template': xeninfo.info['is_a_template'],
            'auto_power_on': False,
            'resident_on': XendNode.instance().uuid,
            'memory_static_min': xeninfo.get_memory_static_min(),
            'memory_static_max': xeninfo.get_memory_static_max(),
            'memory_dynamic_min': xeninfo.get_memory_dynamic_min(),
            'memory_dynamic_max': xeninfo.get_memory_dynamic_max(),
            'VCPUs_params': xeninfo.get_vcpus_params(),
            'VCPUs_at_startup': xeninfo.getVCpuCount(),
            'VCPUs_max': xeninfo.getVCpuCount(),
            'actions_after_shutdown': xeninfo.get_on_shutdown(),
            'actions_after_reboot': xeninfo.get_on_reboot(),
            'actions_after_suspend': xeninfo.get_on_suspend(),
            'actions_after_crash': xeninfo.get_on_crash(),
            'consoles': xeninfo.get_consoles(),
            'VIFs': xeninfo.get_vifs(),
            'VBDs': xeninfo.get_vbds(),
            'VTPMs': xeninfo.get_vtpms(),
            'PV_bootloader': xeninfo.info.get('PV_bootloader'),
            'PV_kernel': xeninfo.info.get('PV_kernel'),
            'PV_ramdisk': xeninfo.info.get('PV_ramdisk'),
            'PV_args': xeninfo.info.get('PV_args'),
            'PV_bootloader_args': xeninfo.info.get('PV_bootloader_args'),
            'HVM_boot_policy': xeninfo.info.get('HVM_boot_policy'),
            'HVM_boot_params': xeninfo.info.get('HVM_boot_params'),
            'platform': xeninfo.get_platform(),
            'PCI_bus': xeninfo.get_pci_bus(),
            'tools_version': xeninfo.get_tools_version(),
            'other_config': xeninfo.info.get('other_config', {}),
            'domid': domid is None and -1 or domid,
            'is_control_domain': xeninfo.info['is_control_domain'],
            'metrics': xeninfo.get_metrics()
        }
        return xen_api_success(record)

    def VM_clean_reboot(self, session, vm_ref):
        xendom = XendDomain.instance()
        xeninfo = xendom.get_vm_by_uuid(vm_ref)
        XendTask.log_progress(0, 100, xeninfo.shutdown, "reboot")
        return xen_api_success_void()
    
    def VM_clean_shutdown(self, session, vm_ref):
        xendom = XendDomain.instance()
        xeninfo = xendom.get_vm_by_uuid(vm_ref)
        XendTask.log_progress(0, 100, xeninfo.shutdown, "poweroff")        
        return xen_api_success_void()
    
    def VM_clone(self, session, vm_ref):
        return xen_api_error(XEND_ERROR_UNSUPPORTED)
    
    def VM_destroy(self, session, vm_ref):
        return XendTask.log_progress(0, 100, do_vm_func,
                                     "domain_delete", vm_ref)
    
    def VM_hard_reboot(self, session, vm_ref):
        return xen_api_error(XEND_ERROR_UNSUPPORTED)
    
    def VM_hard_shutdown(self, session, vm_ref):
        return XendTask.log_progress(0, 100, do_vm_func,
                                     "domain_destroy", vm_ref)    
    def VM_pause(self, session, vm_ref):
        return XendTask.log_progress(0, 100, do_vm_func,
                                     "domain_pause", vm_ref)
    
    def VM_resume(self, session, vm_ref, start_paused):
        return XendTask.log_progress(0, 100, do_vm_func,
                                     "domain_resume", vm_ref,
                                     start_paused = start_paused)
    
    def VM_start(self, session, vm_ref, start_paused):
        try:
            return XendTask.log_progress(0, 100, do_vm_func,
                                         "domain_start", vm_ref,
                                         start_paused = start_paused)
        except HVMRequired, exn:
            return xen_api_error(['VM_HVM_REQUIRED', vm_ref])

    def VM_suspend(self, session, vm_ref):
        return XendTask.log_progress(0, 100, do_vm_func,
                                     "domain_suspend", vm_ref)
    
    def VM_unpause(self, session, vm_ref):
        return XendTask.log_progress(0, 100, do_vm_func,
                                     "domain_unpause", vm_ref)

    def VM_send_sysrq(self, _, vm_ref, req):
        xeninfo = XendDomain.instance().get_vm_by_uuid(vm_ref)
        if xeninfo.state == XEN_API_VM_POWER_STATE_RUNNING \
               or xeninfo.state == XEN_API_VM_POWER_STATE_PAUSED:
            xeninfo.send_sysrq(req)
            return xen_api_success_void()
        else:
            return xen_api_error(
                ['VM_BAD_POWER_STATE', vm_ref,
                 XendDomain.POWER_STATE_NAMES[XEN_API_VM_POWER_STATE_RUNNING],
                 XendDomain.POWER_STATE_NAMES[xeninfo.state]])

    def VM_send_trigger(self, _, vm_ref, trigger, vcpu):
        xendom = XendDomain.instance()
        xeninfo = xendom.get_vm_by_uuid(vm_ref)
        xendom.domain_send_trigger(xeninfo.getDomid(), trigger, vcpu)
        return xen_api_success_void()

    def VM_save(self, _, vm_ref, dest, checkpoint):
        xendom = XendDomain.instance()
        xeninfo = xendom.get_vm_by_uuid(vm_ref)
        xendom.domain_save(xeninfo.getDomid(), dest, checkpoint)
        return xen_api_success_void()

    def VM_restore(self, _, src, paused):
        xendom = XendDomain.instance()
        xendom.domain_restore(src, bool(paused))
        return xen_api_success_void()


    # Xen API: Class VM_metrics
    # ----------------------------------------------------------------

    VM_metrics_attr_ro = ['memory_actual',
                          'VCPUs_number',
                          'VCPUs_utilisation',
                          'VCPUs_CPU',
                          'VCPUs_flags',
                          'VCPUs_params',
                          'state',
                          'start_time',
                          'last_updated']
    VM_metrics_attr_rw = []
    VM_metrics_methods = []

    def _VM_metrics_get(self, _, ref):
        return XendVMMetrics.get_by_uuid(ref)

    def VM_metrics_get_all(self, _):
        return xen_api_success(XendVMMetrics.get_all())


    # Xen API: Class VBD
    # ----------------------------------------------------------------

    VBD_attr_ro = ['VM',
                   'VDI',
                   'metrics',
                   'runtime_properties']
    VBD_attr_rw = ['device',
                   'bootable',
                   'mode',
                   'type']

    VBD_attr_inst = VBD_attr_rw

    VBD_methods = [('media_change', None), ('destroy', None)]
    VBD_funcs = [('create', 'VBD')]
    
    # object methods
    def VBD_get_record(self, session, vbd_ref):
        xendom = XendDomain.instance()
        vm = xendom.get_vm_with_dev_uuid('vbd', vbd_ref)
        if not vm:
            return xen_api_error(['HANDLE_INVALID', 'VBD', vbd_ref])
        cfg = vm.get_dev_xenapi_config('vbd', vbd_ref)
        if not cfg:
            return xen_api_error(['HANDLE_INVALID', 'VBD', vbd_ref])

        valid_vbd_keys = self.VBD_attr_ro + self.VBD_attr_rw + \
                         self.Base_attr_ro + self.Base_attr_rw

        return_cfg = {}
        for k in cfg.keys():
            if k in valid_vbd_keys:
                return_cfg[k] = cfg[k]

        return_cfg['metrics'] = vbd_ref

        return xen_api_success(return_cfg)

    def VBD_media_change(self, session, vbd_ref, vdi_ref):
        return xen_api_error(XEND_ERROR_UNSUPPORTED)

    # class methods
    def VBD_create(self, session, vbd_struct):
        xendom = XendDomain.instance()
        xennode = XendNode.instance()
        
        if not xendom.is_valid_vm(vbd_struct['VM']):
            return xen_api_error(['HANDLE_INVALID', 'VM', vbd_struct['VM']])
        
        dom = xendom.get_vm_by_uuid(vbd_struct['VM'])
        vdi = xennode.get_vdi_by_uuid(vbd_struct['VDI'])
        if not vdi:
            return xen_api_error(['HANDLE_INVALID', 'VDI', vdi_ref])

        # new VBD via VDI/SR
        vdi_image = vdi.get_location()

        try:
            vbd_ref = XendTask.log_progress(0, 100,
                                            dom.create_vbd,
                                            vbd_struct, vdi_image)
        except XendError, e:
            log.exception("Error in VBD_create")
            return xen_api_error(['INTERNAL_ERROR', str(e)]) 
            
        vdi.addVBD(vbd_ref)

        xendom.managed_config_save(dom)
        return xen_api_success(vbd_ref)


    def VBD_destroy(self, session, vbd_ref):
        xendom = XendDomain.instance()
        vm = xendom.get_vm_with_dev_uuid('vbd', vbd_ref)
        if not vm:
            return xen_api_error(['HANDLE_INVALID', 'VBD', vbd_ref])

        vdi_ref = XendDomain.instance()\
                  .get_dev_property_by_uuid('vbd', vbd_ref, "VDI")
        vdi = XendNode.instance().get_vdi_by_uuid(vdi_ref)

        XendTask.log_progress(0, 100, vm.destroy_vbd, vbd_ref)

        vdi.removeVBD(vbd_ref)
        
        return xen_api_success_void()

    def _VBD_get(self, vbd_ref, prop):
        return xen_api_success(
            XendDomain.instance().get_dev_property_by_uuid(
            'vbd', vbd_ref, prop))

    # attributes (ro)
    def VBD_get_metrics(self, _, vbd_ref):
        return xen_api_success(vbd_ref)

    def VBD_get_runtime_properties(self, _, vbd_ref):
        xendom = XendDomain.instance()
        dominfo = xendom.get_vm_with_dev_uuid('vbd', vbd_ref)
        device = dominfo.get_dev_config_by_uuid('vbd', vbd_ref)

        try:
            devid = int(device['id'])
            device_sxps = dominfo.getDeviceSxprs('vbd')
            device_dicts  = [dict(device_sxp[1][1:]) for device_sxp in device_sxps]
            device_dict = [device_dict
                           for device_dict in device_dicts
                           if int(device_dict['virtual-device']) == devid][0]

            return xen_api_success(device_dict)
        except Exception, exn:
            log.exception(exn)
            return xen_api_success({})

    # attributes (rw)
    def VBD_get_VM(self, session, vbd_ref):
        return self._VBD_get(vbd_ref, 'VM')
    
    def VBD_get_VDI(self, session, vbd_ref):
        return self._VBD_get(vbd_ref, 'VDI')

    def VBD_get_device(self, session, vbd_ref):
        return self._VBD_get(vbd_ref, 'device')

    def VBD_get_bootable(self, session, vbd_ref):
        return self._VBD_get(vbd_ref, 'bootable')

    def VBD_get_mode(self, session, vbd_ref):
        return self._VBD_get(vbd_ref, 'mode')

    def VBD_get_type(self, session, vbd_ref):
        return self._VBD_get(vbd_ref, 'type')

    def VBD_set_bootable(self, session, vbd_ref, bootable):
        bootable = bool(bootable)
        xd = XendDomain.instance()
        vm = xd.get_vm_with_dev_uuid('vbd', vbd_ref)
        vm.set_dev_property('vbd', vbd_ref, 'bootable', bootable)
        xd.managed_config_save(vm)
        return xen_api_success_void()

    def VBD_get_all(self, session):
        xendom = XendDomain.instance()
        vbds = [d.get_vbds() for d in XendDomain.instance().list('all')]
        vbds = reduce(lambda x, y: x + y, vbds)
        return xen_api_success(vbds)


    # Xen API: Class VBD_metrics
    # ----------------------------------------------------------------

    VBD_metrics_attr_ro = ['io_read_kbs',
                           'io_write_kbs',
                           'last_updated']
    VBD_metrics_attr_rw = []
    VBD_metrics_methods = []

    def VBD_metrics_get_all(self, session):
        return self.VBD_get_all(session)

    def VBD_metrics_get_record(self, _, ref):
        vm = XendDomain.instance().get_vm_with_dev_uuid('vbd', ref)
        if not vm:
            return xen_api_error(['HANDLE_INVALID', 'VBD_metrics', ref])
        return xen_api_success(
            { 'io_read_kbs'  : vm.get_dev_property('vbd', ref, 'io_read_kbs'),
              'io_write_kbs' : vm.get_dev_property('vbd', ref, 'io_write_kbs'),
              'last_updated' : now()
            })

    def VBD_metrics_get_io_read_kbs(self, _, ref):
        return self._VBD_get(ref, 'io_read_kbs')
    
    def VBD_metrics_get_io_write_kbs(self, session, ref):
        return self._VBD_get(ref, 'io_write_kbs')

    def VBD_metrics_get_last_updated(self, _1, _2):
        return xen_api_success(now())


    # Xen API: Class VIF
    # ----------------------------------------------------------------

    VIF_attr_ro = ['network',
                   'VM',
                   'metrics',
                   'runtime_properties']
    VIF_attr_rw = ['device',
                   'MAC',
                   'MTU']

    VIF_attr_inst = VIF_attr_rw

    VIF_methods = [('destroy', None)]
    VIF_funcs = [('create', 'VIF')]

                 
    # object methods
    def VIF_get_record(self, session, vif_ref):
        xendom = XendDomain.instance()
        vm = xendom.get_vm_with_dev_uuid('vif', vif_ref)
        if not vm:
            return xen_api_error(['HANDLE_INVALID', 'VIF', vif_ref])
        cfg = vm.get_dev_xenapi_config('vif', vif_ref)
        if not cfg:
            return xen_api_error(['HANDLE_INVALID', 'VIF', vif_ref])
        
        valid_vif_keys = self.VIF_attr_ro + self.VIF_attr_rw + \
                         self.Base_attr_ro + self.Base_attr_rw

        return_cfg = {}
        for k in cfg.keys():
            if k in valid_vif_keys:
                return_cfg[k] = cfg[k]
            
        return_cfg['metrics'] = vif_ref

        return xen_api_success(return_cfg)

    # class methods
    def VIF_create(self, session, vif_struct):
        xendom = XendDomain.instance()
        if not xendom.is_valid_vm(vif_struct['VM']):
            return xen_api_error(['HANDLE_INVALID', 'VM', vif_struct['VM']])

        dom = xendom.get_vm_by_uuid(vif_struct['VM'])
        try:
            vif_ref = dom.create_vif(vif_struct)
            xendom.managed_config_save(dom)
            return xen_api_success(vif_ref)
        except XendError:
            return xen_api_error(XEND_ERROR_TODO)
          
    def VIF_destroy(self, session, vif_ref):
        xendom = XendDomain.instance()
        vm = xendom.get_vm_with_dev_uuid('vif', vif_ref)
        if not vm:
            return xen_api_error(['HANDLE_INVALID', 'VIF', vif_ref])

        vm.destroy_vif(vif_ref)
        return xen_api_success_void()

    def _VIF_get(self, ref, prop):
        return xen_api_success(
            XendDomain.instance().get_dev_property_by_uuid('vif', ref, prop))

    # getters/setters
    def VIF_get_metrics(self, _, vif_ref):
        return xen_api_success(vif_ref)

    def VIF_get_VM(self, session, vif_ref):
        xendom = XendDomain.instance()
        vm = xendom.get_vm_with_dev_uuid('vif', vif_ref)
        return xen_api_success(vm.get_uuid())

    def VIF_get_MTU(self, session, vif_ref):
        return self._VIF_get(vif_ref, 'MTU')
    
    def VIF_get_MAC(self, session, vif_ref):
        return self._VIF_get(vif_ref, 'MAC')

    def VIF_get_device(self, session, vif_ref):
        return self._VIF_get(vif_ref, 'device')
 
    def VIF_get_all(self, session):
        xendom = XendDomain.instance()
        vifs = [d.get_vifs() for d in XendDomain.instance().list('all')]
        vifs = reduce(lambda x, y: x + y, vifs)
        return xen_api_success(vifs)

    def VIF_get_runtime_properties(self, _, vif_ref):
        xendom = XendDomain.instance()
        dominfo = xendom.get_vm_with_dev_uuid('vif', vif_ref)
        device = dominfo.get_dev_config_by_uuid('vif', vif_ref)
        
        try:
            devid = int(device['id'])
        
            device_sxps = dominfo.getDeviceSxprs('vif')
            device_dicts = [dict(device_sxp[1][1:])
                            for device_sxp in device_sxps]
            
            device_dict = [device_dict
                       for device_dict in device_dicts
                       if int(device_dict['handle']) == devid][0]
            
            return xen_api_success(device_dict)
        
        except Exception, exn:
            log.exception(exn)
            return xen_api_success({})
    
    # Xen API: Class VIF_metrics
    # ----------------------------------------------------------------

    VIF_metrics_attr_ro = ['io_read_kbs',
                           'io_write_kbs',
                           'last_updated']
    VIF_metrics_attr_rw = []
    VIF_metrics_methods = []

    def VIF_metrics_get_all(self, session):
        return self.VIF_get_all(session)

    def VIF_metrics_get_record(self, _, ref):
        vm = XendDomain.instance().get_vm_with_dev_uuid('vif', ref)
        if not vm:
            return xen_api_error(['HANDLE_INVALID', 'VIF_metrics', ref])
        return xen_api_success(
            { 'io_read_kbs'  : vm.get_dev_property('vif', ref, 'io_read_kbs'),
              'io_write_kbs' : vm.get_dev_property('vif', ref, 'io_write_kbs'),
              'last_updated' : now()
            })

    def VIF_metrics_get_io_read_kbs(self, _, ref):
        return self._VIF_get(ref, 'io_read_kbs')
    
    def VIF_metrics_get_io_write_kbs(self, session, ref):
        return self._VIF_get(ref, 'io_write_kbs')

    def VIF_metrics_get_last_updated(self, _1, _2):
        return xen_api_success(now())


    # Xen API: Class VDI
    # ----------------------------------------------------------------
    VDI_attr_ro = ['SR',
                   'VBDs',
                   'physical_utilisation',
                   'type']
    VDI_attr_rw = ['name_label',
                   'name_description',
                   'virtual_size',
                   'sharable',
                   'read_only',
                   'other_config']
    VDI_attr_inst = VDI_attr_ro + VDI_attr_rw

    VDI_methods = [('snapshot', 'VDI'), ('destroy', None)]
    VDI_funcs = [('create', 'VDI'),
                  ('get_by_name_label', 'Set(VDI)')]

    def _get_VDI(self, ref):
        return XendNode.instance().get_vdi_by_uuid(ref)
    
    def VDI_get_VBDs(self, session, vdi_ref):
        vdi = XendNode.instance().get_vdi_by_uuid(vdi_ref)
        return xen_api_success(vdi.getVBDs())
    
    def VDI_get_physical_utilisation(self, session, vdi_ref):
        return xen_api_success(self._get_VDI(vdi_ref).
                               get_physical_utilisation())              
    
    def VDI_get_type(self, session, vdi_ref):
        return xen_api_success(self._get_VDI(vdi_ref).type)
    
    def VDI_get_name_label(self, session, vdi_ref):
        return xen_api_success(self._get_VDI(vdi_ref).name_label)

    def VDI_get_name_description(self, session, vdi_ref):
        return xen_api_success(self._get_VDI(vdi_ref).name_description)

    def VDI_get_SR(self, session, vdi_ref):
        return xen_api_success(self._get_VDI(vdi_ref).sr_uuid)

    def VDI_get_virtual_size(self, session, vdi_ref):
        return xen_api_success(self._get_VDI(vdi_ref).virtual_size)

    def VDI_get_sharable(self, session, vdi_ref):
        return xen_api_success(self._get_VDI(vdi_ref).sharable)

    def VDI_get_read_only(self, session, vdi_ref):
        return xen_api_success(self._get_VDI(vdi_ref).read_only)        

    def VDI_set_name_label(self, session, vdi_ref, value):
        self._get_VDI(vdi_ref).name_label = value
        return xen_api_success_void()

    def VDI_set_name_description(self, session, vdi_ref, value):
        self._get_VDI(vdi_ref).name_description = value
        return xen_api_success_void()

    def VDI_set_virtual_size(self, session, vdi_ref, value):
        return xen_api_error(XEND_ERROR_UNSUPPORTED)

    def VDI_set_sharable(self, session, vdi_ref, value):
        self._get_VDI(vdi_ref).sharable = bool(value)
        return xen_api_success_void()
    
    def VDI_set_read_only(self, session, vdi_ref, value):
        self._get_VDI(vdi_ref).read_only = bool(value)
        return xen_api_success_void()

    def VDI_get_other_config(self, session, vdi_ref):
        return xen_api_success(
            self._get_VDI(vdi_ref).other_config)

    def VDI_set_other_config(self, session, vdi_ref, other_config):
        self._get_VDI(vdi_ref).other_config = other_config
        return xen_api_success_void()

    # Object Methods
    def VDI_snapshot(self, session, vdi_ref):
        return xen_api_todo()
    
    def VDI_destroy(self, session, vdi_ref):
        sr = XendNode.instance().get_sr_containing_vdi(vdi_ref)
        sr.destroy_vdi(vdi_ref)
        return xen_api_success_void()

    def VDI_get_record(self, session, vdi_ref):
        image = XendNode.instance().get_vdi_by_uuid(vdi_ref)
        return xen_api_success({
            'uuid': vdi_ref,
            'name_label': image.name_label,
            'name_description': image.name_description,
            'SR': image.sr_uuid,
            'VBDs': image.getVBDs(),
            'virtual_size': image.virtual_size,
            'physical_utilisation': image.physical_utilisation,
            'type': image.type,
            'sharable': image.sharable,
            'read_only': image.read_only,
            'other_config': image.other_config
            })

    # Class Functions    
    def VDI_create(self, session, vdi_struct):
        sr_ref = vdi_struct.get('SR')
        xennode = XendNode.instance()
        if not xennode.is_valid_sr(sr_ref):
            return xen_api_error(['HANDLE_INVALID', 'SR', sr_ref])

        vdi_uuid = xennode.srs[sr_ref].create_vdi(vdi_struct)
        return xen_api_success(vdi_uuid)

    def VDI_get_all(self, session):
        xennode = XendNode.instance()
        vdis = [sr.get_vdis() for sr in xennode.srs.values()]
        return xen_api_success(reduce(lambda x, y: x + y, vdis))
    
    def VDI_get_by_name_label(self, session, name):
        xennode = XendNode.instance()
        return xen_api_success(xennode.get_vdi_by_name_label(name))


    # Xen API: Class VTPM
    # ----------------------------------------------------------------

    VTPM_attr_rw = [ ]
    VTPM_attr_ro = ['VM',
                    'backend']

    VTPM_attr_inst = VTPM_attr_rw

    VTPM_methods = [('destroy', None)]
    VTPM_funcs = [('create', 'VTPM')]
    
    # object methods
    def VTPM_get_record(self, session, vtpm_ref):
        xendom = XendDomain.instance()
        vm = xendom.get_vm_with_dev_uuid('vtpm', vtpm_ref)
        if not vm:
            return xen_api_error(['HANDLE_INVALID', 'VTPM', vtpm_ref])
        cfg = vm.get_dev_xenapi_config('vtpm', vtpm_ref)
        if not cfg:
            return xen_api_error(['HANDLE_INVALID', 'VTPM', vtpm_ref])
        valid_vtpm_keys = self.VTPM_attr_ro + self.VTPM_attr_rw + \
                          self.Base_attr_ro + self.Base_attr_rw
        return_cfg = {}
        for k in cfg.keys():
            if k in valid_vtpm_keys:
                return_cfg[k] = cfg[k]

        return xen_api_success(return_cfg)

    # Class Functions
    def VTPM_get_backend(self, session, vtpm_ref):
        xendom = XendDomain.instance()
        vm = xendom.get_vm_with_dev_uuid('vtpm', vtpm_ref)
        if not vm:
            return xen_api_error(['HANDLE_INVALID', 'VTPM', vtpm_ref])
        cfg = vm.get_dev_xenapi_config('vtpm', vtpm_ref)
        if not cfg:
            return xen_api_error(['HANDLE_INVALID', 'VTPM', vtpm_ref])
        if not cfg.has_key('backend'):
            return xen_api_error(['VTPM backend not set'])
        return xen_api_success(cfg['backend'])

    def VTPM_get_VM(self, session, vtpm_ref):
        xendom = XendDomain.instance()
        return xen_api_success(xendom.get_dev_property_by_uuid('vtpm',
                                                              vtpm_ref, 'VM'))

    def VTPM_destroy(self, session, vtpm_ref):
        xendom = XendDomain.instance()
        dom = xendom.get_vm_with_dev_uuid('vtpm', vtpm_ref)
        if dom:
            if dom.state != XEN_API_VM_POWER_STATE_HALTED:
                vm_ref = dom.get_dev_property('vtpm', vtpm_ref, 'VM')
                return xen_api_error(['VM_BAD_POWER_STATE', vm_ref,
                 XendDomain.POWER_STATE_NAMES[XEN_API_VM_POWER_STATE_HALTED],
                 XendDomain.POWER_STATE_NAMES[dom.state]])
            from xen.xend.server import tpmif
            tpmif.destroy_vtpmstate(dom.getName())
            return xen_api_success_void()
        else:
            return xen_api_error(['HANDLE_INVALID', 'VM', vtpm_struct['VM']])

    # class methods
    def VTPM_create(self, session, vtpm_struct):
        xendom = XendDomain.instance()
        if xendom.is_valid_vm(vtpm_struct['VM']):
            dom = xendom.get_vm_by_uuid(vtpm_struct['VM'])
            try:
                vtpm_ref = dom.create_vtpm(vtpm_struct)
                xendom.managed_config_save(dom)
                return xen_api_success(vtpm_ref)
            except XendError:
                return xen_api_error(XEND_ERROR_TODO)
        else:
            return xen_api_error(['HANDLE_INVALID', 'VM', vtpm_struct['VM']])

    def VTPM_get_all(self, session):
        xendom = XendDomain.instance()
        vtpms = [d.get_vtpms() for d in XendDomain.instance().list('all')]
        vtpms = reduce(lambda x, y: x + y, vtpms)
        return xen_api_success(vtpms)

    # Xen API: Class console
    # ----------------------------------------------------------------


    console_attr_ro = ['location', 'protocol', 'VM']
    console_attr_rw = ['other_config']
    console_funcs = [('create', 'console')]
    
    def console_get_all(self, session):
        xendom = XendDomain.instance()
        cons = [d.get_consoles() for d in XendDomain.instance().list('all')]
        cons = reduce(lambda x, y: x + y, cons)
        return xen_api_success(cons)

    def console_get_location(self, session, console_ref):
        return xen_api_success(xendom.get_dev_property_by_uuid('console',
                                                               console_ref,
                                                               'location'))

    def console_get_protocol(self, session, console_ref):
        return xen_api_success(xendom.get_dev_property_by_uuid('console',
                                                               console_ref,
                                                               'protocol'))
    
    def console_get_VM(self, session, console_ref):
        xendom = XendDomain.instance()        
        vm = xendom.get_vm_with_dev_uuid('console', console_ref)
        return xen_api_success(vm.get_uuid())
    
    # object methods
    def console_get_record(self, session, console_ref):
        xendom = XendDomain.instance()
        vm = xendom.get_vm_with_dev_uuid('console', console_ref)
        if not vm:
            return xen_api_error(['HANDLE_INVALID', 'console', console_ref])
        cfg = vm.get_dev_xenapi_config('console', console_ref)
        if not cfg:
            return xen_api_error(['HANDLE_INVALID', 'console', console_ref])
        
        valid_console_keys = self.console_attr_ro + self.console_attr_rw + \
                             self.Base_attr_ro + self.Base_attr_rw

        return_cfg = {}
        for k in cfg.keys():
            if k in valid_console_keys:
                return_cfg[k] = cfg[k]
            
        return xen_api_success(return_cfg)

    def console_create(self, session, console_struct):
        xendom = XendDomain.instance()
        if not xendom.is_valid_vm(console_struct['VM']):
            return xen_api_error(['HANDLE_INVALID', 'VM',
                                  console_struct['VM']])
        
        dom = xendom.get_vm_by_uuid(console_struct['VM'])
        try:
            if 'protocol' not in console_struct:
                return xen_api_error(['CONSOLE_PROTOCOL_INVALID',
                                      'No protocol specified'])
            
            console_ref = dom.create_console(console_struct)
            xendom.managed_config_save(dom)
            return xen_api_success(console_ref)
        except XendError, e:
            return xen_api_error([XEND_ERROR_TODO, str(e)])

    # Xen API: Class SR
    # ----------------------------------------------------------------
    SR_attr_ro = ['VDIs',
                  'virtual_allocation',
                  'physical_utilisation',
                  'physical_size',
                  'type',
                  'location']
    
    SR_attr_rw = ['name_label',
                  'name_description']
    
    SR_attr_inst = ['physical_size',
                    'type',
                    'location',
                    'name_label',
                    'name_description']
    
    SR_methods = [('clone', 'SR'), ('destroy', None)]
    SR_funcs = [('get_by_name_label', 'Set(SR)'),
                ('get_by_uuid', 'SR')]

    # Class Functions
    def SR_get_all(self, session):
        return xen_api_success(XendNode.instance().get_all_sr_uuid())
  
    def SR_get_by_name_label(self, session, label):
        return xen_api_success(XendNode.instance().get_sr_by_name(label))
    
    def SR_create(self, session):
        return xen_api_error(XEND_ERROR_UNSUPPORTED)

    # Class Methods
    def SR_clone(self, session, sr_ref):
        return xen_api_error(XEND_ERROR_UNSUPPORTED)
    
    def SR_destroy(self, session, sr_ref):
        return xen_api_error(XEND_ERROR_UNSUPPORTED)
    
    def SR_get_record(self, session, sr_ref):
        sr = XendNode.instance().get_sr(sr_ref)
        if sr:
            return xen_api_success(sr.get_record())
        return xen_api_error(['HANDLE_INVALID', 'SR', sr_ref])

    # Attribute acceess

    def _get_SR_func(self, sr_ref, func):
        return xen_api_success(getattr(XendNode.instance().get_sr(sr_ref),
                                       func)())

    def _get_SR_attr(self, sr_ref, attr):
        return xen_api_success(getattr(XendNode.instance().get_sr(sr_ref),
                                       attr))

    def SR_get_VDIs(self, _, ref):
        return self._get_SR_func(ref, 'list_images')

    def SR_get_virtual_allocation(self, _, ref):
        return self._get_SR_func(ref, 'virtual_allocation')

    def SR_get_physical_utilisation(self, _, ref):
        return self._get_SR_func(ref, 'physical_utilisation')

    def SR_get_physical_size(self, _, ref):
        return self._get_SR_func(ref, 'physical_size')
    
    def SR_get_type(self, _, ref):
        return self._get_SR_attr(ref, 'type')

    def SR_get_location(self, _, ref):
        return self._get_SR_attr(ref, 'location')

    def SR_get_name_label(self, _, ref):
        return self._get_SR_attr(ref, 'name_label')
    
    def SR_get_name_description(self, _, ref):
        return self._get_SR_attr(ref, 'name_description')

    def SR_set_name_label(self, session, sr_ref, value):
        sr = XendNode.instance.get_sr(sr_ref)
        if sr:
            sr.name_label = value
            XendNode.instance().save()
        return xen_api_success_void()
    
    def SR_set_name_description(self, session, sr_ref, value):
        sr = XendNode.instance.get_sr(sr_ref)