1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 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 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724
|
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from openstack.cloud import _network_common
from openstack.cloud import _utils
from openstack.cloud import exc
from openstack import exceptions
class NetworkCloudMixin(_network_common.NetworkCommonCloudMixin):
def _neutron_extensions(self):
extensions = set()
for extension in self.network.extensions():
extensions.add(extension['alias'])
return extensions
def _has_neutron_extension(self, extension_alias):
return extension_alias in self._neutron_extensions()
# TODO(stephenfin): Deprecate this in favour of the 'list' function
def search_networks(self, name_or_id=None, filters=None):
"""Search networks
:param name_or_id: Name or ID of the desired network.
:param filters: A dict containing additional filters to use. e.g.
{'router:external': True}
:returns: A list of network ``Network`` objects matching the search
criteria.
:raises: :class:`~openstack.exceptions.SDKException` if something goes
wrong during the OpenStack API call.
"""
query = {}
if name_or_id:
query['name'] = name_or_id
if filters:
query.update(filters)
return list(self.network.networks(**query))
# TODO(stephenfin): Deprecate this in favour of the 'list' function
def search_routers(self, name_or_id=None, filters=None):
"""Search routers
:param name_or_id: Name or ID of the desired router.
:param filters: A dict containing additional filters to use. e.g.
{'admin_state_up': True}
:returns: A list of network ``Router`` objects matching the search
criteria.
:raises: :class:`~openstack.exceptions.SDKException` if something goes
wrong during the OpenStack API call.
"""
query = {}
if name_or_id:
query['name'] = name_or_id
if filters:
query.update(filters)
return list(self.network.routers(**query))
# TODO(stephenfin): Deprecate this in favour of the 'list' function
def search_subnets(self, name_or_id=None, filters=None):
"""Search subnets
:param name_or_id: Name or ID of the desired subnet.
:param filters: A dict containing additional filters to use. e.g.
{'enable_dhcp': True}
:returns: A list of network ``Subnet`` objects matching the search
criteria.
:raises: :class:`~openstack.exceptions.SDKException` if something goes
wrong during the OpenStack API call.
"""
query = {}
if name_or_id:
query['name'] = name_or_id
if filters:
query.update(filters)
return list(self.network.subnets(**query))
# TODO(stephenfin): Deprecate this in favour of the 'list' function
def search_ports(self, name_or_id=None, filters=None):
"""Search ports
:param name_or_id: Name or ID of the desired port.
:param filters: A dict containing additional filters to use. e.g.
{'device_id': '2711c67a-b4a7-43dd-ace7-6187b791c3f0'}
:returns: A list of network ``Port`` objects matching the search
criteria.
:raises: :class:`~openstack.exceptions.SDKException` if something goes
wrong during the OpenStack API call.
"""
# If the filter is a string, do not push the filter down to neutron;
# get all the ports and filter locally.
# TODO(stephenfin): '_filter_list' can handle a dict - pass it down
if isinstance(filters, str):
pushdown_filters = None
else:
pushdown_filters = filters
ports = self.list_ports(pushdown_filters)
return _utils._filter_list(ports, name_or_id, filters)
def list_networks(self, filters=None):
"""List all available networks.
:param filters: (optional) A dict of filter conditions to push down.
:returns: A list of network ``Network`` objects.
"""
# If the cloud is running nova-network, just return an empty list.
if not self.has_service('network'):
return []
# Translate None from search interface to empty {} for kwargs below
if not filters:
filters = {}
return list(self.network.networks(**filters))
def list_routers(self, filters=None):
"""List all available routers.
:param filters: (optional) A dict of filter conditions to push down
:returns: A list of network ``Router`` objects.
"""
# If the cloud is running nova-network, just return an empty list.
if not self.has_service('network'):
return []
# Translate None from search interface to empty {} for kwargs below
if not filters:
filters = {}
return list(self.network.routers(**filters))
def list_subnets(self, filters=None):
"""List all available subnets.
:param filters: (optional) A dict of filter conditions to push down
:returns: A list of network ``Subnet`` objects.
"""
# If the cloud is running nova-network, just return an empty list.
if not self.has_service('network'):
return []
# Translate None from search interface to empty {} for kwargs below
if not filters:
filters = {}
return list(self.network.subnets(**filters))
def list_ports(self, filters=None):
"""List all available ports.
:param filters: (optional) A dict of filter conditions to push down
:returns: A list of network ``Port`` objects.
"""
# If the cloud is running nova-network, just return an empty list.
if not self.has_service('network'):
return []
# Translate None from search interface to empty {} for kwargs below
if not filters:
filters = {}
return list(self.network.ports(**filters))
# TODO(stephenfin): Deprecate 'filters'; users should use 'list' for this
def get_qos_policy(self, name_or_id, filters=None):
"""Get a QoS policy by name or ID.
:param name_or_id: Name or ID of the policy.
:param filters: A dictionary of meta data to use for further filtering.
Elements of this dictionary may, themselves, be dictionaries.
Example::
{'last_name': 'Smith', 'other': {'gender': 'Female'}}
OR
A string containing a jmespath expression for further filtering.
Example:: "[?last_name==`Smith`] | [?other.gender]==`Female`]"
:returns: A network ``QoSPolicy`` object if found, else None.
"""
if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension(
'QoS extension is not available on target cloud'
)
if not filters:
filters = {}
return self.network.find_qos_policy(
name_or_id=name_or_id, ignore_missing=True, **filters
)
# TODO(stephenfin): Deprecate this in favour of the 'list' function
def search_qos_policies(self, name_or_id=None, filters=None):
"""Search QoS policies
:param name_or_id: Name or ID of the desired policy.
:param filters: a dict containing additional filters to use. e.g.
{'shared': True}
:returns: A list of network ``QosPolicy`` objects matching the search
criteria.
:raises: :class:`~openstack.exceptions.SDKException` if something goes
wrong during the OpenStack API call.
"""
if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension(
'QoS extension is not available on target cloud'
)
query = {}
if name_or_id:
query['name'] = name_or_id
if filters:
query.update(filters)
return list(self.network.qos_policies(**query))
def list_qos_rule_types(self, filters=None):
"""List all available QoS rule types.
:param filters: (optional) A dict of filter conditions to push down
:returns: A list of network ``QosRuleType`` objects.
"""
if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension(
'QoS extension is not available on target cloud'
)
# Translate None from search interface to empty {} for kwargs below
if not filters:
filters = {}
return list(self.network.qos_rule_types(**filters))
# TODO(stephenfin): Deprecate 'filters'; users should use 'list' for this
def get_qos_rule_type_details(self, rule_type, filters=None):
"""Get a QoS rule type details by rule type name.
:param rule_type: Name of the QoS rule type.
:param filters: A dictionary of meta data to use for further filtering.
Elements of this dictionary may, themselves, be dictionaries.
Example::
{'last_name': 'Smith', 'other': {'gender': 'Female'}}
OR
A string containing a jmespath expression for further filtering.
Example:: "[?last_name==`Smith`] | [?other.gender]==`Female`]"
:returns: A network ``QoSRuleType`` object if found, else None.
"""
if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension(
'QoS extension is not available on target cloud'
)
if not self._has_neutron_extension('qos-rule-type-details'):
raise exc.OpenStackCloudUnavailableExtension(
'qos-rule-type-details extension is not available '
'on target cloud'
)
return self.network.get_qos_rule_type(rule_type)
def list_qos_policies(self, filters=None):
"""List all available QoS policies.
:param filters: (optional) A dict of filter conditions to push down
:returns: A list of network ``QosPolicy`` objects.
"""
if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension(
'QoS extension is not available on target cloud'
)
# Translate None from search interface to empty {} for kwargs below
if not filters:
filters = {}
return list(self.network.qos_policies(**filters))
# TODO(stephenfin): Deprecate 'filters'; users should use 'list' for this
def get_network(self, name_or_id, filters=None):
"""Get a network by name or ID.
:param name_or_id: Name or ID of the network.
:param filters: A dictionary of meta data to use for further filtering.
Elements of this dictionary may, themselves, be dictionaries.
Example::
{'last_name': 'Smith', 'other': {'gender': 'Female'}}
OR
A string containing a jmespath expression for further filtering.
Example:: "[?last_name==`Smith`] | [?other.gender]==`Female`]"
:returns: A network ``Network`` object if found, else None.
"""
if not filters:
filters = {}
return self.network.find_network(
name_or_id=name_or_id, ignore_missing=True, **filters
)
def get_network_by_id(self, id):
"""Get a network by ID
:param id: ID of the network.
:returns: A network ``Network`` object if found, else None.
"""
return self.network.get_network(id)
# TODO(stephenfin): Deprecate 'filters'; users should use 'list' for this
def get_router(self, name_or_id, filters=None):
"""Get a router by name or ID.
:param name_or_id: Name or ID of the router.
:param filters: A dictionary of meta data to use for further filtering.
Elements of this dictionary may, themselves, be dictionaries.
Example::
{'last_name': 'Smith', 'other': {'gender': 'Female'}}
OR
A string containing a jmespath expression for further filtering.
Example:: "[?last_name==`Smith`] | [?other.gender]==`Female`]"
:returns: A network ``Router`` object if found, else None.
"""
if not filters:
filters = {}
return self.network.find_router(
name_or_id=name_or_id, ignore_missing=True, **filters
)
# TODO(stephenfin): Deprecate 'filters'; users should use 'list' for this
def get_subnet(self, name_or_id, filters=None):
"""Get a subnet by name or ID.
:param name_or_id: Name or ID of the subnet.
:param filters: A dictionary of meta data to use for further filtering.
Elements of this dictionary may, themselves, be dictionaries.
Example::
{'last_name': 'Smith', 'other': {'gender': 'Female'}}
:returns: A network ``Subnet`` object if found, else None.
"""
if not filters:
filters = {}
return self.network.find_subnet(
name_or_id=name_or_id, ignore_missing=True, **filters
)
def get_subnet_by_id(self, id):
"""Get a subnet by ID
:param id: ID of the subnet.
:returns: A network ``Subnet`` object if found, else None.
"""
return self.network.get_subnet(id)
# TODO(stephenfin): Deprecate 'filters'; users should use 'list' for this
def get_port(self, name_or_id, filters=None):
"""Get a port by name or ID.
:param name_or_id: Name or ID of the port.
:param filters: A dictionary of meta data to use for further filtering.
Elements of this dictionary may, themselves, be dictionaries.
Example::
{'last_name': 'Smith', 'other': {'gender': 'Female'}}
OR
A string containing a jmespath expression for further filtering.
Example:: "[?last_name==`Smith`] | [?other.gender]==`Female`]"
:returns: A network ``Port`` object if found, else None.
"""
if not filters:
filters = {}
return self.network.find_port(
name_or_id=name_or_id, ignore_missing=True, **filters
)
def get_port_by_id(self, id):
"""Get a port by ID
:param id: ID of the port.
:returns: A network ``Port`` object if found, else None.
"""
return self.network.get_port(id)
def get_subnetpool(self, name_or_id):
"""Get a subnetpool by name or ID.
:param name_or_id: Name or ID of the subnetpool.
:returns: A network ``Subnetpool`` object if found, else None.
"""
return self.network.find_subnet_pool(
name_or_id=name_or_id, ignore_missing=True
)
def create_network(
self,
name,
shared=False,
admin_state_up=True,
external=False,
provider=None,
project_id=None,
availability_zone_hints=None,
port_security_enabled=None,
mtu_size=None,
dns_domain=None,
):
"""Create a network.
:param string name: Name of the network being created.
:param bool shared: Set the network as shared.
:param bool admin_state_up: Set the network administrative state to up.
:param bool external: Whether this network is externally accessible.
:param dict provider: A dict of network provider options. Example::
{'network_type': 'vlan', 'segmentation_id': 'vlan1'}
:param string project_id: Specify the project ID this network
will be created on (admin-only).
:param types.ListType availability_zone_hints: A list of availability
zone hints.
:param bool port_security_enabled: Enable / Disable port security
:param int mtu_size: maximum transmission unit value to address
fragmentation. Minimum value is 68 for IPv4, and 1280 for IPv6.
:param string dns_domain: Specify the DNS domain associated with
this network.
:returns: The created network ``Network`` object.
:raises: :class:`~openstack.exceptions.SDKException` on operation
error.
"""
network = {
'name': name,
'admin_state_up': admin_state_up,
}
if shared:
network['shared'] = shared
if project_id is not None:
network['project_id'] = project_id
if availability_zone_hints is not None:
if not isinstance(availability_zone_hints, list):
raise exceptions.SDKException(
"Parameter 'availability_zone_hints' must be a list"
)
if not self._has_neutron_extension('network_availability_zone'):
raise exc.OpenStackCloudUnavailableExtension(
'network_availability_zone extension is not available on '
'target cloud'
)
network['availability_zone_hints'] = availability_zone_hints
if provider:
if not isinstance(provider, dict):
raise exceptions.SDKException(
"Parameter 'provider' must be a dict"
)
# Only pass what we know
for attr in (
'physical_network',
'network_type',
'segmentation_id',
):
if attr in provider:
arg = "provider:" + attr
network[arg] = provider[attr]
# Do not send 'router:external' unless it is explicitly
# set since sending it *might* cause "Forbidden" errors in
# some situations. It defaults to False in the client, anyway.
if external:
network['router:external'] = True
if port_security_enabled is not None:
if not isinstance(port_security_enabled, bool):
raise exceptions.SDKException(
"Parameter 'port_security_enabled' must be a bool"
)
network['port_security_enabled'] = port_security_enabled
if mtu_size:
if not isinstance(mtu_size, int):
raise exceptions.SDKException(
"Parameter 'mtu_size' must be an integer."
)
if not mtu_size >= 68:
raise exceptions.SDKException(
"Parameter 'mtu_size' must be greater than 67."
)
network['mtu'] = mtu_size
if dns_domain:
network['dns_domain'] = dns_domain
network = self.network.create_network(**network)
# Reset cache so the new network is picked up
self._reset_network_caches()
return network
@_utils.valid_kwargs(
"name",
"shared",
"admin_state_up",
"external",
"provider",
"mtu_size",
"port_security_enabled",
"dns_domain",
)
def update_network(self, name_or_id, **kwargs):
"""Update a network.
:param string name_or_id: Name or ID of the network being updated.
:param string name: New name of the network.
:param bool shared: Set the network as shared.
:param bool admin_state_up: Set the network administrative state to up.
:param bool external: Whether this network is externally accessible.
:param dict provider: A dict of network provider options. Example::
{'network_type': 'vlan', 'segmentation_id': 'vlan1'}
:param int mtu_size: New maximum transmission unit value to address
fragmentation. Minimum value is 68 for IPv4, and 1280 for IPv6.
:param bool port_security_enabled: Enable or disable port security.
:param string dns_domain: Specify the DNS domain associated with
this network.
:returns: The updated network ``Network`` object.
:raises: :class:`~openstack.exceptions.SDKException` on operation
error.
"""
provider = kwargs.pop('provider', None)
if provider:
if not isinstance(provider, dict):
raise exceptions.SDKException(
"Parameter 'provider' must be a dict"
)
for key in ('physical_network', 'network_type', 'segmentation_id'):
if key in provider:
kwargs['provider:' + key] = provider.pop(key)
if 'external' in kwargs:
kwargs['router:external'] = kwargs.pop('external')
if 'port_security_enabled' in kwargs:
if not isinstance(kwargs['port_security_enabled'], bool):
raise exceptions.SDKException(
"Parameter 'port_security_enabled' must be a bool"
)
if 'mtu_size' in kwargs:
if not isinstance(kwargs['mtu_size'], int):
raise exceptions.SDKException(
"Parameter 'mtu_size' must be an integer."
)
if kwargs['mtu_size'] < 68:
raise exceptions.SDKException(
"Parameter 'mtu_size' must be greater than 67."
)
kwargs['mtu'] = kwargs.pop('mtu_size')
network = self.get_network(name_or_id)
if not network:
raise exceptions.SDKException(f"Network {name_or_id} not found.")
network = self.network.update_network(network, **kwargs)
self._reset_network_caches()
return network
def delete_network(self, name_or_id):
"""Delete a network.
:param name_or_id: Name or ID of the network being deleted.
:returns: True if delete succeeded, False otherwise.
:raises: :class:`~openstack.exceptions.SDKException` on operation
error.
"""
network = self.get_network(name_or_id)
if not network:
self.log.debug("Network %s not found for deleting", name_or_id)
return False
self.network.delete_network(network)
# Reset cache so the deleted network is removed
self._reset_network_caches()
return True
def set_network_quotas(self, name_or_id, **kwargs):
"""Set a network quota in a project
:param name_or_id: project name or id
:param kwargs: key/value pairs of quota name and quota value
:raises: :class:`~openstack.exceptions.SDKException` if the resource to
set the quota does not exist.
"""
proj = self.identity.find_project(name_or_id, ignore_missing=True)
if not proj:
raise exceptions.SDKException(
f"Project {name_or_id} was requested by was not found "
f"on the cloud"
)
self.network.update_quota(proj.id, **kwargs)
def get_network_quotas(self, name_or_id, details=False):
"""Get network quotas for a project
:param name_or_id: project name or id
:param details: if set to True it will return details about usage
of quotas by given project
:returns: A network ``Quota`` object if found, else None.
:raises: :class:`~openstack.exceptions.SDKException` if it's not a
valid project
"""
proj = self.identity.find_project(name_or_id, ignore_missing=True)
if not proj:
raise exc.OpenStackCloudException(
f"Project {name_or_id} was requested by was not found "
f"on the cloud"
)
return self.network.get_quota(proj.id, details)
def get_network_extensions(self):
"""Get Cloud provided network extensions
:returns: A set of Neutron extension aliases.
"""
return self._neutron_extensions()
def delete_network_quotas(self, name_or_id):
"""Delete network quotas for a project
:param name_or_id: project name or id
:returns: dict with the quotas
:raises: :class:`~openstack.exceptions.SDKException` if it's not a
valid project or the network client call failed
"""
proj = self.identity.find_project(name_or_id, ignore_missing=True)
if not proj:
raise exceptions.SDKException(
f"Project {name_or_id} was requested by was not found "
f"on the cloud"
)
self.network.delete_quota(proj.id)
@_utils.valid_kwargs(
'action',
'description',
'destination_firewall_group_id',
'destination_ip_address',
'destination_port',
'enabled',
'ip_version',
'name',
'project_id',
'protocol',
'shared',
'source_firewall_group_id',
'source_ip_address',
'source_port',
)
def create_firewall_rule(self, **kwargs):
"""
Creates firewall rule.
:param action: Action performed on traffic.
Valid values: allow, deny
Defaults to deny.
:param description: Human-readable description.
:param destination_firewall_group_id: ID of destination firewall group.
:param destination_ip_address: IPv4-, IPv6 address or CIDR.
:param destination_port: Port or port range (e.g. 80:90)
:param bool enabled: Status of firewall rule. You can disable rules
without disassociating them from firewall policies. Defaults to
True.
:param int ip_version: IP Version. Valid values: 4, 6 Defaults to 4.
:param name: Human-readable name.
:param project_id: Project id.
:param protocol: IP protocol. Valid values: icmp, tcp, udp, null
:param bool shared: Visibility to other projects. Defaults to False.
:param source_firewall_group_id: ID of source firewall group.
:param source_ip_address: IPv4-, IPv6 address or CIDR.
:param source_port: Port or port range (e.g. 80:90)
:raises: BadRequestException if parameters are malformed
:returns: The created network ``FirewallRule`` object.
"""
return self.network.create_firewall_rule(**kwargs)
def delete_firewall_rule(self, name_or_id, filters=None):
"""
Deletes firewall rule.
Prints debug message in case to-be-deleted resource was not found.
:param name_or_id: firewall rule name or id
:param filters: A dictionary of meta data to use for further filtering.
Elements of this dictionary may, themselves, be dictionaries.
Example::
{'last_name': 'Smith', 'other': {'gender': 'Female'}}
OR
A string containing a jmespath expression for further filtering.
Example:: "[?last_name==`Smith`] | [?other.gender]==`Female`]"
:raises: DuplicateResource on multiple matches
:returns: True if resource is successfully deleted, False otherwise.
:rtype: bool
"""
if not filters:
filters = {}
try:
firewall_rule = self.network.find_firewall_rule(
name_or_id, ignore_missing=False, **filters
)
self.network.delete_firewall_rule(
firewall_rule, ignore_missing=False
)
except exceptions.NotFoundException:
self.log.debug(
'Firewall rule %s not found for deleting', name_or_id
)
return False
return True
# TODO(stephenfin): Deprecate 'filters'; users should use 'list' for this
def get_firewall_rule(self, name_or_id, filters=None):
"""
Retrieves a single firewall rule.
:param name_or_id: firewall rule name or id
:param filters: A dictionary of meta data to use for further filtering.
Elements of this dictionary may, themselves, be dictionaries.
Example::
{'last_name': 'Smith', 'other': {'gender': 'Female'}}
OR
A string containing a jmespath expression for further filtering.
Example:: "[?last_name==`Smith`] | [?other.gender]==`Female`]"
:raises: DuplicateResource on multiple matches
:returns: A network ``FirewallRule`` object if found, else None.
"""
if not filters:
filters = {}
return self.network.find_firewall_rule(
name_or_id, ignore_missing=True, **filters
)
def list_firewall_rules(self, filters=None):
"""
Lists firewall rules.
:param filters: A dictionary of meta data to use for further filtering.
Elements of this dictionary may, themselves, be dictionaries.
Example::
{'last_name': 'Smith', 'other': {'gender': 'Female'}}
OR
A string containing a jmespath expression for further filtering.
Example:: "[?last_name==`Smith`] | [?other.gender]==`Female`]"
:returns: A list of network ``FirewallRule`` objects.
:rtype: list[FirewallRule]
"""
if not filters:
filters = {}
return list(self.network.firewall_rules(**filters))
@_utils.valid_kwargs(
'action',
'description',
'destination_firewall_group_id',
'destination_ip_address',
'destination_port',
'enabled',
'ip_version',
'name',
'project_id',
'protocol',
'shared',
'source_firewall_group_id',
'source_ip_address',
'source_port',
)
def update_firewall_rule(self, name_or_id, filters=None, **kwargs):
"""
Updates firewall rule.
:param name_or_id: firewall rule name or id
:param filters: A dictionary of meta data to use for further filtering.
Elements of this dictionary may, themselves, be dictionaries.
Example::
{'last_name': 'Smith', 'other': {'gender': 'Female'}}
OR
A string containing a jmespath expression for further filtering.
Example:: "[?last_name==`Smith`] | [?other.gender]==`Female`]"
:param kwargs: firewall rule update parameters.
See create_firewall_rule docstring for valid parameters.
:returns: The updated network ``FirewallRule`` object.
:raises: BadRequestException if parameters are malformed
:raises: NotFoundException if resource is not found
"""
if not filters:
filters = {}
firewall_rule = self.network.find_firewall_rule(
name_or_id, ignore_missing=False, **filters
)
return self.network.update_firewall_rule(firewall_rule, **kwargs)
def _get_firewall_rule_ids(self, name_or_id_list, filters=None):
"""
Takes a list of firewall rule name or ids, looks them up and returns
a list of firewall rule ids.
Used by `create_firewall_policy` and `update_firewall_policy`.
:param list[str] name_or_id_list: firewall rule name or id list
:param dict filters: optional filters
:raises: DuplicateResource on multiple matches
:raises: NotFoundException if resource is not found
:return: list of firewall rule ids
:rtype: list[str]
"""
if not filters:
filters = {}
ids_list = []
for name_or_id in name_or_id_list:
ids_list.append(
self.network.find_firewall_rule(
name_or_id, ignore_missing=False, **filters
)['id']
)
return ids_list
@_utils.valid_kwargs(
'audited',
'description',
'firewall_rules',
'name',
'project_id',
'shared',
)
def create_firewall_policy(self, **kwargs):
"""
Create firewall policy.
:param bool audited: Status of audition of firewall policy.
Set to False each time the firewall policy or the associated
firewall rules are changed. Has to be explicitly set to True.
:param description: Human-readable description.
:param list[str] firewall_rules: List of associated firewall rules.
:param name: Human-readable name.
:param project_id: Project id.
:param bool shared: Visibility to other projects.
Defaults to False.
:raises: BadRequestException if parameters are malformed
:raises: NotFoundException if a resource from firewall_list not found
:returns: The created network ``FirewallPolicy`` object.
"""
if 'firewall_rules' in kwargs:
kwargs['firewall_rules'] = self._get_firewall_rule_ids(
kwargs['firewall_rules']
)
return self.network.create_firewall_policy(**kwargs)
def delete_firewall_policy(self, name_or_id, filters=None):
"""
Deletes firewall policy.
Prints debug message in case to-be-deleted resource was not found.
:param name_or_id: firewall policy name or id
:param filters: A dictionary of meta data to use for further filtering.
Elements of this dictionary may, themselves, be dictionaries.
Example::
{'last_name': 'Smith', 'other': {'gender': 'Female'}}
OR
A string containing a jmespath expression for further filtering.
Example:: "[?last_name==`Smith`] | [?other.gender]==`Female`]"
:raises: DuplicateResource on multiple matches
:returns: True if resource is successfully deleted, False otherwise.
:rtype: bool
"""
if not filters:
filters = {}
try:
firewall_policy = self.network.find_firewall_policy(
name_or_id, ignore_missing=False, **filters
)
self.network.delete_firewall_policy(
firewall_policy, ignore_missing=False
)
except exceptions.NotFoundException:
self.log.debug(
'Firewall policy %s not found for deleting', name_or_id
)
return False
return True
# TODO(stephenfin): Deprecate 'filters'; users should use 'list' for this
def get_firewall_policy(self, name_or_id, filters=None):
"""
Retrieves a single firewall policy.
:param name_or_id: firewall policy name or id
:param filters: A dictionary of meta data to use for further filtering.
Elements of this dictionary may, themselves, be dictionaries.
Example::
{'last_name': 'Smith', 'other': {'gender': 'Female'}}
OR
A string containing a jmespath expression for further filtering.
Example:: "[?last_name==`Smith`] | [?other.gender]==`Female`]"
:raises: DuplicateResource on multiple matches
:returns: A network ``FirewallPolicy`` object if found, else None.
"""
if not filters:
filters = {}
return self.network.find_firewall_policy(
name_or_id, ignore_missing=True, **filters
)
def list_firewall_policies(self, filters=None):
"""
Lists firewall policies.
:param filters: A dictionary of meta data to use for further filtering.
Elements of this dictionary may, themselves, be dictionaries.
Example::
{'last_name': 'Smith', 'other': {'gender': 'Female'}}
OR
A string containing a jmespath expression for further filtering.
Example:: "[?last_name==`Smith`] | [?other.gender]==`Female`]"
:returns: A list of network ``FirewallPolicy`` objects.
:rtype: list[FirewallPolicy]
"""
if not filters:
filters = {}
return list(self.network.firewall_policies(**filters))
@_utils.valid_kwargs(
'audited',
'description',
'firewall_rules',
'name',
'project_id',
'shared',
)
def update_firewall_policy(self, name_or_id, filters=None, **kwargs):
"""
Updates firewall policy.
:param name_or_id: firewall policy name or id
:param filters: A dictionary of meta data to use for further filtering.
Elements of this dictionary may, themselves, be dictionaries.
Example::
{'last_name': 'Smith', 'other': {'gender': 'Female'}}
OR
A string containing a jmespath expression for further filtering.
Example:: "[?last_name==`Smith`] | [?other.gender]==`Female`]"
:param kwargs: firewall policy update parameters
See create_firewall_policy docstring for valid parameters.
:returns: The updated network ``FirewallPolicy`` object.
:raises: BadRequestException if parameters are malformed
:raises: DuplicateResource on multiple matches
:raises: NotFoundException if resource is not found
"""
if not filters:
filters = {}
firewall_policy = self.network.find_firewall_policy(
name_or_id, ignore_missing=False, **filters
)
if 'firewall_rules' in kwargs:
kwargs['firewall_rules'] = self._get_firewall_rule_ids(
kwargs['firewall_rules']
)
return self.network.update_firewall_policy(firewall_policy, **kwargs)
def insert_rule_into_policy(
self,
name_or_id,
rule_name_or_id,
insert_after=None,
insert_before=None,
filters=None,
):
"""Add firewall rule to a policy.
Adds firewall rule to the firewall_rules list of a firewall policy.
Short-circuits and returns the firewall policy early if the firewall
rule id is already present in the firewall_rules list.
This method doesn't do re-ordering. If you want to move a firewall rule
or down the list, you have to remove and re-add it.
:param name_or_id: firewall policy name or id
:param rule_name_or_id: firewall rule name or id
:param insert_after: rule name or id that should precede added rule
:param insert_before: rule name or id that should succeed added rule
:param dict filters: optional filters
:raises: DuplicateResource on multiple matches
:raises: NotFoundException if firewall policy or any of the firewall
rules (inserted, after, before) is not found.
:return: updated firewall policy
:rtype: FirewallPolicy
"""
if not filters:
filters = {}
firewall_policy = self.network.find_firewall_policy(
name_or_id, ignore_missing=False, **filters
)
firewall_rule = self.network.find_firewall_rule(
rule_name_or_id, ignore_missing=False
)
# short-circuit if rule already in firewall_rules list
# the API can't do any re-ordering of existing rules
if firewall_rule['id'] in firewall_policy['firewall_rules']:
self.log.debug(
'Firewall rule %s already associated with firewall policy %s',
rule_name_or_id,
name_or_id,
)
return firewall_policy
pos_params = {}
if insert_after is not None:
pos_params['insert_after'] = self.network.find_firewall_rule(
insert_after, ignore_missing=False
)['id']
if insert_before is not None:
pos_params['insert_before'] = self.network.find_firewall_rule(
insert_before, ignore_missing=False
)['id']
return self.network.insert_rule_into_policy(
firewall_policy['id'], firewall_rule['id'], **pos_params
)
def remove_rule_from_policy(
self, name_or_id, rule_name_or_id, filters=None
):
"""
Remove firewall rule from firewall policy's firewall_rules list.
Short-circuits and returns firewall policy early if firewall rule
is already absent from the firewall_rules list.
:param name_or_id: firewall policy name or id
:param rule_name_or_id: firewall rule name or id
:param dict filters: optional filters
:raises: DuplicateResource on multiple matches
:raises: NotFoundException if firewall policy is not found
:return: updated firewall policy
:rtype: FirewallPolicy
"""
if not filters:
filters = {}
firewall_policy = self.network.find_firewall_policy(
name_or_id, ignore_missing=False, **filters
)
firewall_rule = self.network.find_firewall_rule(rule_name_or_id)
if not firewall_rule:
# short-circuit: if firewall rule is not found,
# return current firewall policy
self.log.debug(
'Firewall rule %s not found for removing', rule_name_or_id
)
return firewall_policy
if firewall_rule['id'] not in firewall_policy['firewall_rules']:
# short-circuit: if firewall rule id is not associated,
# log it to debug and return current firewall policy
self.log.debug(
'Firewall rule %s not associated with firewall policy %s',
rule_name_or_id,
name_or_id,
)
return firewall_policy
return self.network.remove_rule_from_policy(
firewall_policy['id'], firewall_rule['id']
)
@_utils.valid_kwargs(
'admin_state_up',
'description',
'egress_firewall_policy',
'ingress_firewall_policy',
'name',
'ports',
'project_id',
'shared',
)
def create_firewall_group(self, **kwargs):
"""
Creates firewall group. The keys egress_firewall_policy and
ingress_firewall_policy are looked up and mapped as
egress_firewall_policy_id and ingress_firewall_policy_id respectively.
Port name or ids list is transformed to port ids list before the POST
request.
:param bool admin_state_up: State of firewall group.
Will block all traffic if set to False. Defaults to True.
:param description: Human-readable description.
:param egress_firewall_policy: Name or id of egress firewall policy.
:param ingress_firewall_policy: Name or id of ingress firewall policy.
:param name: Human-readable name.
:param list[str] ports: List of associated ports (name or id)
:param project_id: Project id.
:param shared: Visibility to other projects. Defaults to False.
:raises: BadRequestException if parameters are malformed
:raises: DuplicateResource on multiple matches
:raises: NotFoundException if (ingress-, egress-) firewall policy or
a port is not found.
:returns: The created network ``FirewallGroup`` object.
"""
self._lookup_ingress_egress_firewall_policy_ids(kwargs)
if 'ports' in kwargs:
kwargs['ports'] = self._get_port_ids(kwargs['ports'])
return self.network.create_firewall_group(**kwargs)
def delete_firewall_group(self, name_or_id, filters=None):
"""
Deletes firewall group.
Prints debug message in case to-be-deleted resource was not found.
:param name_or_id: firewall group name or id
:param dict filters: optional filters
:raises: DuplicateResource on multiple matches
:returns: True if resource is successfully deleted, False otherwise.
:rtype: bool
"""
if not filters:
filters = {}
try:
firewall_group = self.network.find_firewall_group(
name_or_id, ignore_missing=False, **filters
)
self.network.delete_firewall_group(
firewall_group, ignore_missing=False
)
except exceptions.NotFoundException:
self.log.debug(
'Firewall group %s not found for deleting', name_or_id
)
return False
return True
# TODO(stephenfin): Deprecate 'filters'; users should use 'list' for this
def get_firewall_group(self, name_or_id, filters=None):
"""
Retrieves firewall group.
:param name_or_id: firewall group name or id
:param dict filters: optional filters
:raises: DuplicateResource on multiple matches
:returns: A network ``FirewallGroup`` object if found, else None.
"""
if not filters:
filters = {}
return self.network.find_firewall_group(
name_or_id, ignore_missing=True, **filters
)
def list_firewall_groups(self, filters=None):
"""
Lists firewall groups.
:returns: A list of network ``FirewallGroup`` objects.
"""
if not filters:
filters = {}
return list(self.network.firewall_groups(**filters))
@_utils.valid_kwargs(
'admin_state_up',
'description',
'egress_firewall_policy',
'ingress_firewall_policy',
'name',
'ports',
'project_id',
'shared',
)
def update_firewall_group(self, name_or_id, filters=None, **kwargs):
"""
Updates firewall group.
To unset egress- or ingress firewall policy, set egress_firewall_policy
or ingress_firewall_policy to None. You can also set
egress_firewall_policy_id and ingress_firewall_policy_id directly,
which will skip the policy lookups.
:param name_or_id: firewall group name or id
:param dict filters: optional filters
:param kwargs: firewall group update parameters
See create_firewall_group docstring for valid parameters.
:returns: The updated network ``FirewallGroup`` object.
:raises: BadRequestException if parameters are malformed
:raises: DuplicateResource on multiple matches
:raises: NotFoundException if firewall group, a firewall policy
(egress, ingress) or port is not found
"""
if not filters:
filters = {}
firewall_group = self.network.find_firewall_group(
name_or_id, ignore_missing=False, **filters
)
self._lookup_ingress_egress_firewall_policy_ids(kwargs)
if 'ports' in kwargs:
kwargs['ports'] = self._get_port_ids(kwargs['ports'])
return self.network.update_firewall_group(firewall_group, **kwargs)
def _lookup_ingress_egress_firewall_policy_ids(self, firewall_group):
"""
Transforms firewall_group dict IN-PLACE. Takes the value of the keys
egress_firewall_policy and ingress_firewall_policy, looks up the
policy ids and maps them to egress_firewall_policy_id and
ingress_firewall_policy_id. Old keys which were used for the lookup
are deleted.
:param dict firewall_group: firewall group dict
:raises: DuplicateResource on multiple matches
:raises: NotFoundException if a firewall policy is not found
"""
for key in ('egress_firewall_policy', 'ingress_firewall_policy'):
if key not in firewall_group:
continue
if firewall_group[key] is None:
val = None
else:
val = self.network.find_firewall_policy(
firewall_group[key], ignore_missing=False
)['id']
firewall_group[key + '_id'] = val
del firewall_group[key]
@_utils.valid_kwargs(
"name", "description", "shared", "default", "project_id"
)
def create_qos_policy(self, **kwargs):
"""Create a QoS policy.
:param string name: Name of the QoS policy being created.
:param string description: Description of created QoS policy.
:param bool shared: Set the QoS policy as shared.
:param bool default: Set the QoS policy as default for project.
:param string project_id: Specify the project ID this QoS policy
will be created on (admin-only).
:returns: The created network ``QosPolicy`` object.
:raises: :class:`~openstack.exceptions.SDKException` on operation
error.
"""
if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension(
'QoS extension is not available on target cloud'
)
default = kwargs.pop("default", None)
if default is not None:
if self._has_neutron_extension('qos-default'):
kwargs['is_default'] = default
else:
self.log.debug(
"'qos-default' extension is not available on target cloud"
)
return self.network.create_qos_policy(**kwargs)
@_utils.valid_kwargs(
"name", "description", "shared", "default", "project_id"
)
def update_qos_policy(self, name_or_id, **kwargs):
"""Update an existing QoS policy.
:param string name_or_id: Name or ID of the QoS policy to update.
:param string policy_name: The new name of the QoS policy.
:param string description: The new description of the QoS policy.
:param bool shared: If True, the QoS policy will be set as shared.
:param bool default: If True, the QoS policy will be set as default for
project.
:returns: The updated network ``QosPolicyRule`` object.
:raises: :class:`~openstack.exceptions.SDKException` on operation
error.
"""
if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension(
'QoS extension is not available on target cloud'
)
default = kwargs.pop("default", None)
if default is not None:
if self._has_neutron_extension('qos-default'):
kwargs['is_default'] = default
else:
self.log.debug(
"'qos-default' extension is not available on target cloud"
)
if not kwargs:
self.log.debug("No QoS policy data to update")
return
curr_policy = self.network.find_qos_policy(
name_or_id, ignore_missing=True
)
if not curr_policy:
raise exceptions.SDKException(
f"QoS policy {name_or_id} not found."
)
return self.network.update_qos_policy(curr_policy, **kwargs)
def delete_qos_policy(self, name_or_id):
"""Delete a QoS policy.
:param name_or_id: Name or ID of the policy being deleted.
:returns: True if delete succeeded, False otherwise.
:raises: :class:`~openstack.exceptions.SDKException` on operation
error.
"""
if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension(
'QoS extension is not available on target cloud'
)
policy = self.network.find_qos_policy(name_or_id, ignore_missing=True)
if not policy:
self.log.debug("QoS policy %s not found for deleting", name_or_id)
return False
self.network.delete_qos_policy(policy)
return True
# TODO(stephenfin): Deprecate this in favour of the 'list' function
def search_qos_bandwidth_limit_rules(
self,
policy_name_or_id,
rule_id=None,
filters=None,
):
"""Search QoS bandwidth limit rules
:param string policy_name_or_id: Name or ID of the QoS policy to which
rules should be associated.
:param string rule_id: ID of searched rule.
:param filters: a dict containing additional filters to use. e.g.
{'max_kbps': 1000}
:returns: A list of network ``QoSBandwidthLimitRule`` objects matching
the search criteria.
:raises: :class:`~openstack.exceptions.SDKException` if something goes
wrong during the OpenStack API call.
"""
rules = self.list_qos_bandwidth_limit_rules(policy_name_or_id, filters)
return _utils._filter_list(rules, rule_id, filters)
def list_qos_bandwidth_limit_rules(self, policy_name_or_id, filters=None):
"""List all available QoS bandwidth limit rules.
:param string policy_name_or_id: Name or ID of the QoS policy from
from rules should be listed.
:param filters: (optional) A dict of filter conditions to push down
:returns: A list of network ``QoSBandwidthLimitRule`` objects.
:raises: ``:class:`~openstack.exceptions.BadRequestException``` if QoS
policy will not be found.
"""
if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension(
'QoS extension is not available on target cloud'
)
policy = self.network.find_qos_policy(
policy_name_or_id, ignore_missing=True
)
if not policy:
raise exceptions.NotFoundException(
f"QoS policy {policy_name_or_id} not Found."
)
# Translate None from search interface to empty {} for kwargs below
if not filters:
filters = {}
return list(
self.network.qos_bandwidth_limit_rules(
qos_policy=policy, **filters
)
)
def get_qos_bandwidth_limit_rule(self, policy_name_or_id, rule_id):
"""Get a QoS bandwidth limit rule by name or ID.
:param string policy_name_or_id: Name or ID of the QoS policy to which
rule should be associated.
:param rule_id: ID of the rule.
:returns: A network ``QoSBandwidthLimitRule`` object if found, else
None.
"""
if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension(
'QoS extension is not available on target cloud'
)
policy = self.network.find_qos_policy(
policy_name_or_id, ignore_missing=True
)
if not policy:
raise exceptions.NotFoundException(
f"QoS policy {policy_name_or_id} not Found."
)
return self.network.get_qos_bandwidth_limit_rule(rule_id, policy)
@_utils.valid_kwargs("max_burst_kbps", "direction")
def create_qos_bandwidth_limit_rule(
self,
policy_name_or_id,
max_kbps,
**kwargs,
):
"""Create a QoS bandwidth limit rule.
:param string policy_name_or_id: Name or ID of the QoS policy to which
rule should be associated.
:param int max_kbps: Maximum bandwidth limit value
(in kilobits per second).
:param int max_burst_kbps: Maximum burst value (in kilobits).
:param string direction: Ingress or egress.
The direction in which the traffic will be limited.
:returns: The created network ``QoSBandwidthLimitRule`` object.
:raises: :class:`~openstack.exceptions.SDKException` on operation
error.
"""
if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension(
'QoS extension is not available on target cloud'
)
policy = self.network.find_qos_policy(
policy_name_or_id, ignore_missing=True
)
if not policy:
raise exceptions.NotFoundException(
f"QoS policy {policy_name_or_id} not Found."
)
if kwargs.get("direction") is not None:
if not self._has_neutron_extension('qos-bw-limit-direction'):
kwargs.pop("direction")
self.log.debug(
"'qos-bw-limit-direction' extension is not available on "
"target cloud"
)
kwargs['max_kbps'] = max_kbps
return self.network.create_qos_bandwidth_limit_rule(policy, **kwargs)
@_utils.valid_kwargs("max_kbps", "max_burst_kbps", "direction")
def update_qos_bandwidth_limit_rule(
self, policy_name_or_id, rule_id, **kwargs
):
"""Update a QoS bandwidth limit rule.
:param string policy_name_or_id: Name or ID of the QoS policy to which
rule is associated.
:param string rule_id: ID of rule to update.
:param int max_kbps: Maximum bandwidth limit value
(in kilobits per second).
:param int max_burst_kbps: Maximum burst value (in kilobits).
:param string direction: Ingress or egress.
The direction in which the traffic will be limited.
:returns: The updated network ``QoSBandwidthLimitRule`` object.
:raises: :class:`~openstack.exceptions.SDKException` on operation
error.
"""
if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension(
'QoS extension is not available on target cloud'
)
policy = self.network.find_qos_policy(
policy_name_or_id, ignore_missing=True
)
if not policy:
raise exceptions.NotFoundException(
f"QoS policy {policy_name_or_id} not Found."
)
if kwargs.get("direction") is not None:
if not self._has_neutron_extension('qos-bw-limit-direction'):
kwargs.pop("direction")
self.log.debug(
"'qos-bw-limit-direction' extension is not available on "
"target cloud"
)
if not kwargs:
self.log.debug("No QoS bandwidth limit rule data to update")
return
curr_rule = self.network.get_qos_bandwidth_limit_rule(
qos_rule=rule_id, qos_policy=policy
)
if not curr_rule:
raise exceptions.SDKException(
"QoS bandwidth_limit_rule {rule_id} not found in policy "
"{policy_id}".format(rule_id=rule_id, policy_id=policy['id'])
)
return self.network.update_qos_bandwidth_limit_rule(
qos_rule=curr_rule, qos_policy=policy, **kwargs
)
def delete_qos_bandwidth_limit_rule(self, policy_name_or_id, rule_id):
"""Delete a QoS bandwidth limit rule.
:param string policy_name_or_id: Name or ID of the QoS policy to which
rule is associated.
:param string rule_id: ID of rule to update.
:raises: :class:`~openstack.exceptions.SDKException` on operation
error.
"""
if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension(
'QoS extension is not available on target cloud'
)
policy = self.network.find_qos_policy(
policy_name_or_id, ignore_missing=True
)
if not policy:
raise exceptions.NotFoundException(
f"QoS policy {policy_name_or_id} not Found."
)
try:
self.network.delete_qos_bandwidth_limit_rule(
rule_id, policy, ignore_missing=False
)
except exceptions.NotFoundException:
self.log.debug(
"QoS bandwidth limit rule {rule_id} not found in policy "
"{policy_id}. Ignoring.".format(
rule_id=rule_id, policy_id=policy['id']
)
)
return False
return True
# TODO(stephenfin): Deprecate this in favour of the 'list' function
def search_qos_dscp_marking_rules(
self,
policy_name_or_id,
rule_id=None,
filters=None,
):
"""Search QoS DSCP marking rules
:param string policy_name_or_id: Name or ID of the QoS policy to which
rules should be associated.
:param string rule_id: ID of searched rule.
:param filters: a dict containing additional filters to use. e.g.
{'dscp_mark': 32}
:returns: A list of network ``QoSDSCPMarkingRule`` objects matching the
search criteria.
:raises: :class:`~openstack.exceptions.SDKException` if something goes
wrong during the OpenStack API call.
"""
rules = self.list_qos_dscp_marking_rules(policy_name_or_id, filters)
return _utils._filter_list(rules, rule_id, filters)
def list_qos_dscp_marking_rules(self, policy_name_or_id, filters=None):
"""List all available QoS DSCP marking rules.
:param string policy_name_or_id: Name or ID of the QoS policy from
from rules should be listed.
:param filters: (optional) A dict of filter conditions to push down
:returns: A list of network ``QoSDSCPMarkingRule`` objects.
:raises: ``:class:`~openstack.exceptions.BadRequestException``` if QoS
policy will not be found.
"""
if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension(
'QoS extension is not available on target cloud'
)
policy = self.network.find_qos_policy(
policy_name_or_id, ignore_missing=True
)
if not policy:
raise exceptions.NotFoundException(
f"QoS policy {policy_name_or_id} not Found."
)
# Translate None from search interface to empty {} for kwargs below
if not filters:
filters = {}
return list(self.network.qos_dscp_marking_rules(policy, **filters))
def get_qos_dscp_marking_rule(self, policy_name_or_id, rule_id):
"""Get a QoS DSCP marking rule by name or ID.
:param string policy_name_or_id: Name or ID of the QoS policy to which
rule should be associated.
:param rule_id: ID of the rule.
:returns: A network ``QoSDSCPMarkingRule`` object if found, else None.
"""
if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension(
'QoS extension is not available on target cloud'
)
policy = self.network.find_qos_policy(
policy_name_or_id, ignore_missing=True
)
if not policy:
raise exceptions.NotFoundException(
f"QoS policy {policy_name_or_id} not Found."
)
return self.network.get_qos_dscp_marking_rule(rule_id, policy)
def create_qos_dscp_marking_rule(
self,
policy_name_or_id,
dscp_mark,
):
"""Create a QoS DSCP marking rule.
:param string policy_name_or_id: Name or ID of the QoS policy to which
rule should be associated.
:param int dscp_mark: DSCP mark value
:returns: The created network ``QoSDSCPMarkingRule`` object.
:raises: :class:`~openstack.exceptions.SDKException` on operation
error.
"""
if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension(
'QoS extension is not available on target cloud'
)
policy = self.network.find_qos_policy(
policy_name_or_id, ignore_missing=True
)
if not policy:
raise exceptions.NotFoundException(
f"QoS policy {policy_name_or_id} not Found."
)
return self.network.create_qos_dscp_marking_rule(
policy, dscp_mark=dscp_mark
)
@_utils.valid_kwargs("dscp_mark")
def update_qos_dscp_marking_rule(
self, policy_name_or_id, rule_id, **kwargs
):
"""Update a QoS DSCP marking rule.
:param string policy_name_or_id: Name or ID of the QoS policy to which
rule is associated.
:param string rule_id: ID of rule to update.
:param int dscp_mark: DSCP mark value
:returns: The updated network ``QoSDSCPMarkingRule`` object.
:raises: :class:`~openstack.exceptions.SDKException` on operation
error.
"""
if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension(
'QoS extension is not available on target cloud'
)
policy = self.network.find_qos_policy(
policy_name_or_id, ignore_missing=True
)
if not policy:
raise exceptions.NotFoundException(
f"QoS policy {policy_name_or_id} not Found."
)
if not kwargs:
self.log.debug("No QoS DSCP marking rule data to update")
return
curr_rule = self.network.get_qos_dscp_marking_rule(rule_id, policy)
if not curr_rule:
raise exceptions.SDKException(
"QoS dscp_marking_rule {rule_id} not found in policy "
"{policy_id}".format(rule_id=rule_id, policy_id=policy['id'])
)
return self.network.update_qos_dscp_marking_rule(
curr_rule, policy, **kwargs
)
def delete_qos_dscp_marking_rule(self, policy_name_or_id, rule_id):
"""Delete a QoS DSCP marking rule.
:param string policy_name_or_id: Name or ID of the QoS policy to which
rule is associated.
:param string rule_id: ID of rule to update.
:raises: :class:`~openstack.exceptions.SDKException` on operation
error.
"""
if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension(
'QoS extension is not available on target cloud'
)
policy = self.network.find_qos_policy(
policy_name_or_id, ignore_missing=True
)
if not policy:
raise exceptions.NotFoundException(
f"QoS policy {policy_name_or_id} not Found."
)
try:
self.network.delete_qos_dscp_marking_rule(
rule_id, policy, ignore_missing=False
)
except exceptions.NotFoundException:
self.log.debug(
"QoS DSCP marking rule {rule_id} not found in policy "
"{policy_id}. Ignoring.".format(
rule_id=rule_id, policy_id=policy['id']
)
)
return False
return True
# TODO(stephenfin): Deprecate this in favour of the 'list' function
def search_qos_minimum_bandwidth_rules(
self,
policy_name_or_id,
rule_id=None,
filters=None,
):
"""Search QoS minimum bandwidth rules
:param string policy_name_or_id: Name or ID of the QoS policy to which
rules should be associated.
:param string rule_id: ID of searched rule.
:param filters: a dict containing additional filters to use. e.g.
{'min_kbps': 1000}
:returns: A list of network ``QoSMinimumBandwidthRule`` objects
matching the search criteria.
:raises: :class:`~openstack.exceptions.SDKException` if something goes
wrong during the OpenStack API call.
"""
rules = self.list_qos_minimum_bandwidth_rules(
policy_name_or_id, filters
)
return _utils._filter_list(rules, rule_id, filters)
def list_qos_minimum_bandwidth_rules(
self, policy_name_or_id, filters=None
):
"""List all available QoS minimum bandwidth rules.
:param string policy_name_or_id: Name or ID of the QoS policy from
from rules should be listed.
:param filters: (optional) A dict of filter conditions to push down
:returns: A list of network ``QoSMinimumBandwidthRule`` objects.
:raises: ``:class:`~openstack.exceptions.BadRequestException``` if QoS
policy will not be found.
"""
if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension(
'QoS extension is not available on target cloud'
)
policy = self.network.find_qos_policy(
policy_name_or_id, ignore_missing=True
)
if not policy:
raise exceptions.NotFoundException(
f"QoS policy {policy_name_or_id} not Found."
)
# Translate None from search interface to empty {} for kwargs below
if not filters:
filters = {}
return list(
self.network.qos_minimum_bandwidth_rules(policy, **filters)
)
def get_qos_minimum_bandwidth_rule(self, policy_name_or_id, rule_id):
"""Get a QoS minimum bandwidth rule by name or ID.
:param string policy_name_or_id: Name or ID of the QoS policy to which
rule should be associated.
:param rule_id: ID of the rule.
:returns: A network ``QoSMinimumBandwidthRule`` object if found, else
None.
"""
if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension(
'QoS extension is not available on target cloud'
)
policy = self.network.find_qos_policy(
policy_name_or_id, ignore_missing=True
)
if not policy:
raise exceptions.NotFoundException(
f"QoS policy {policy_name_or_id} not Found."
)
return self.network.get_qos_minimum_bandwidth_rule(rule_id, policy)
@_utils.valid_kwargs("direction")
def create_qos_minimum_bandwidth_rule(
self,
policy_name_or_id,
min_kbps,
**kwargs,
):
"""Create a QoS minimum bandwidth limit rule.
:param string policy_name_or_id: Name or ID of the QoS policy to which
rule should be associated.
:param int min_kbps: Minimum bandwidth value (in kilobits per second).
:param string direction: Ingress or egress.
The direction in which the traffic will be available.
:returns: The created network ``QoSMinimumBandwidthRule`` object.
:raises: :class:`~openstack.exceptions.SDKException` on operation
error.
"""
if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension(
'QoS extension is not available on target cloud'
)
policy = self.network.find_qos_policy(
policy_name_or_id, ignore_missing=True
)
if not policy:
raise exceptions.NotFoundException(
f"QoS policy {policy_name_or_id} not Found."
)
kwargs['min_kbps'] = min_kbps
return self.network.create_qos_minimum_bandwidth_rule(policy, **kwargs)
@_utils.valid_kwargs("min_kbps", "direction")
def update_qos_minimum_bandwidth_rule(
self, policy_name_or_id, rule_id, **kwargs
):
"""Update a QoS minimum bandwidth rule.
:param string policy_name_or_id: Name or ID of the QoS policy to which
rule is associated.
:param string rule_id: ID of rule to update.
:param int min_kbps: Minimum bandwidth value (in kilobits per second).
:param string direction: Ingress or egress.
The direction in which the traffic will be available.
:returns: The updated network ``QoSMinimumBandwidthRule`` object.
:raises: :class:`~openstack.exceptions.SDKException` on operation
error.
"""
if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension(
'QoS extension is not available on target cloud'
)
policy = self.network.find_qos_policy(
policy_name_or_id, ignore_missing=True
)
if not policy:
raise exceptions.NotFoundException(
f"QoS policy {policy_name_or_id} not Found."
)
if not kwargs:
self.log.debug("No QoS minimum bandwidth rule data to update")
return
curr_rule = self.network.get_qos_minimum_bandwidth_rule(
rule_id, policy
)
if not curr_rule:
raise exceptions.SDKException(
"QoS minimum_bandwidth_rule {rule_id} not found in policy "
"{policy_id}".format(rule_id=rule_id, policy_id=policy['id'])
)
return self.network.update_qos_minimum_bandwidth_rule(
curr_rule, policy, **kwargs
)
def delete_qos_minimum_bandwidth_rule(self, policy_name_or_id, rule_id):
"""Delete a QoS minimum bandwidth rule.
:param string policy_name_or_id: Name or ID of the QoS policy to which
rule is associated.
:param string rule_id: ID of rule to delete.
:raises: :class:`~openstack.exceptions.SDKException` on operation
error.
"""
if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension(
'QoS extension is not available on target cloud'
)
policy = self.network.find_qos_policy(
policy_name_or_id, ignore_missing=True
)
if not policy:
raise exceptions.NotFoundException(
f"QoS policy {policy_name_or_id} not Found."
)
try:
self.network.delete_qos_minimum_bandwidth_rule(
rule_id, policy, ignore_missing=False
)
except exceptions.NotFoundException:
self.log.debug(
"QoS minimum bandwidth rule {rule_id} not found in policy "
"{policy_id}. Ignoring.".format(
rule_id=rule_id, policy_id=policy['id']
)
)
return False
return True
def add_router_interface(self, router, subnet_id=None, port_id=None):
"""Attach a subnet to an internal router interface.
Either a subnet ID or port ID must be specified for the internal
interface. Supplying both will result in an error.
:param dict router: The dict object of the router being changed
:param string subnet_id: The ID of the subnet to use for the interface
:param string port_id: The ID of the port to use for the interface
:returns: The raw response body from the request.
:raises: :class:`~openstack.exceptions.SDKException` on operation
error.
"""
return self.network.add_interface_to_router(
router=router, subnet_id=subnet_id, port_id=port_id
)
def remove_router_interface(self, router, subnet_id=None, port_id=None):
"""Detach a subnet from an internal router interface.
At least one of subnet_id or port_id must be supplied.
If you specify both subnet and port ID, the subnet ID must
correspond to the subnet ID of the first IP address on the port
specified by the port ID. Otherwise an error occurs.
:param dict router: The dict object of the router being changed
:param string subnet_id: The ID of the subnet to use for the interface
:param string port_id: The ID of the port to use for the interface
:returns: None on success
:raises: :class:`~openstack.exceptions.SDKException` on operation
error.
"""
if not subnet_id and not port_id:
raise ValueError(
"At least one of subnet_id or port_id must be supplied."
)
self.network.remove_interface_from_router(
router=router, subnet_id=subnet_id, port_id=port_id
)
def list_router_interfaces(self, router, interface_type=None):
"""List all interfaces for a router.
:param dict router: A router dict object.
:param string interface_type: One of None, "internal", or "external".
Controls whether all, internal interfaces or external interfaces
are returned.
:returns: A list of network ``Port`` objects.
"""
# Find only router interface and gateway ports, ignore L3 HA ports etc.
ports = list(self.network.ports(device_id=router['id']))
router_interfaces = (
[
port
for port in ports
if (
port['device_owner']
in [
'network:router_interface',
'network:router_interface_distributed',
'network:ha_router_replicated_interface',
]
)
]
if not interface_type or interface_type == 'internal'
else []
)
router_gateways = (
[
port
for port in ports
if port['device_owner'] == 'network:router_gateway'
]
if not interface_type or interface_type == 'external'
else []
)
return router_interfaces + router_gateways
def create_router(
self,
name=None,
admin_state_up=True,
ext_gateway_net_id=None,
enable_snat=None,
ext_fixed_ips=None,
project_id=None,
availability_zone_hints=None,
):
"""Create a logical router.
:param string name: The router name.
:param bool admin_state_up: The administrative state of the router.
:param string ext_gateway_net_id: Network ID for the external gateway.
:param bool enable_snat: Enable Source NAT (SNAT) attribute.
:param ext_fixed_ips:
List of dictionaries of desired IP and/or subnet on the
external network. Example::
[
{
"subnet_id": "8ca37218-28ff-41cb-9b10-039601ea7e6b",
"ip_address": "192.168.10.2",
}
]
:param string project_id: Project ID for the router.
:param types.ListType availability_zone_hints: A list of availability
zone hints.
:returns: The created network ``Router`` object.
:raises: :class:`~openstack.exceptions.SDKException` on operation
error.
"""
router = {'admin_state_up': admin_state_up}
if project_id is not None:
router['project_id'] = project_id
if name:
router['name'] = name
ext_gw_info = self._build_external_gateway_info(
ext_gateway_net_id, enable_snat, ext_fixed_ips
)
if ext_gw_info:
router['external_gateway_info'] = ext_gw_info
if availability_zone_hints is not None:
if not isinstance(availability_zone_hints, list):
raise exceptions.SDKException(
"Parameter 'availability_zone_hints' must be a list"
)
if not self._has_neutron_extension('router_availability_zone'):
raise exc.OpenStackCloudUnavailableExtension(
'router_availability_zone extension is not available on '
'target cloud'
)
router['availability_zone_hints'] = availability_zone_hints
return self.network.create_router(**router)
def update_router(
self,
name_or_id,
name=None,
admin_state_up=None,
ext_gateway_net_id=None,
enable_snat=None,
ext_fixed_ips=None,
routes=None,
):
"""Update an existing logical router.
:param string name_or_id: The name or UUID of the router to update.
:param string name: The new router name.
:param bool admin_state_up: The administrative state of the router.
:param string ext_gateway_net_id:
The network ID for the external gateway.
:param bool enable_snat: Enable Source NAT (SNAT) attribute.
:param ext_fixed_ips:
List of dictionaries of desired IP and/or subnet on the
external network. Example::
[
{
"subnet_id": "8ca37218-28ff-41cb-9b10-039601ea7e6b",
"ip_address": "192.168.10.2",
}
]
:param list routes:
A list of dictionaries with destination and nexthop parameters. To
clear all routes pass an empty list ([]).
Example::
[{"destination": "179.24.1.0/24", "nexthop": "172.24.3.99"}]
:returns: The updated network ``Router`` object.
:raises: :class:`~openstack.exceptions.SDKException` on operation
error.
"""
router = {}
if name:
router['name'] = name
if admin_state_up is not None:
router['admin_state_up'] = admin_state_up
ext_gw_info = self._build_external_gateway_info(
ext_gateway_net_id, enable_snat, ext_fixed_ips
)
if ext_gw_info:
router['external_gateway_info'] = ext_gw_info
if routes is not None:
if self._has_neutron_extension('extraroute'):
router['routes'] = routes
else:
self.log.warning(
'extra routes extension is not available on target cloud'
)
if not router:
self.log.debug("No router data to update")
return
curr_router = self.get_router(name_or_id)
if not curr_router:
raise exceptions.SDKException(f"Router {name_or_id} not found.")
return self.network.update_router(curr_router, **router)
def delete_router(self, name_or_id):
"""Delete a logical router.
If a name, instead of a unique UUID, is supplied, it is possible
that we could find more than one matching router since names are
not required to be unique. An error will be raised in this case.
:param name_or_id: Name or ID of the router being deleted.
:returns: True if delete succeeded, False otherwise.
:raises: :class:`~openstack.exceptions.SDKException` on operation
error.
"""
router = self.network.find_router(name_or_id, ignore_missing=True)
if not router:
self.log.debug("Router %s not found for deleting", name_or_id)
return False
self.network.delete_router(router)
return True
def create_subnet(
self,
network_name_or_id,
cidr=None,
ip_version=4,
enable_dhcp=False,
subnet_name=None,
tenant_id=None,
allocation_pools=None,
gateway_ip=None,
disable_gateway_ip=False,
dns_nameservers=None,
host_routes=None,
ipv6_ra_mode=None,
ipv6_address_mode=None,
prefixlen=None,
use_default_subnetpool=False,
subnetpool_name_or_id=None,
**kwargs,
):
"""Create a subnet on a specified network.
:param string network_name_or_id: The unique name or ID of the attached
network. If a non-unique name is supplied, an exception is raised.
:param string cidr: The CIDR. Only one of ``cidr``,
``use_default_subnetpool`` and ``subnetpool_name_or_id`` may be
specified at the same time.
:param int ip_version: The IP version, which is 4 or 6.
:param bool enable_dhcp: Set to ``True`` if DHCP is enabled and
``False`` if disabled. Default is ``False``.
:param string subnet_name: The name of the subnet.
:param string tenant_id: The ID of the tenant who owns the network.
Only administrative users can specify a tenant ID other than their
own.
:param allocation_pools: A list of dictionaries of the start and end
addresses for the allocation pools. For example::
[{"start": "192.168.199.2", "end": "192.168.199.254"}]
:param string gateway_ip: The gateway IP address. When you specify both
allocation_pools and gateway_ip, you must ensure that the gateway
IP does not overlap with the specified allocation pools.
:param bool disable_gateway_ip: Set to ``True`` if gateway IP address
is disabled and ``False`` if enabled. It is not allowed with
gateway_ip. Default is ``False``.
:param dns_nameservers: A list of DNS name servers for the subnet. For
example::
["8.8.8.7", "8.8.8.8"]
:param host_routes: A list of host route dictionaries for the subnet.
For example::
[
{"destination": "0.0.0.0/0", "nexthop": "123.456.78.9"},
{"destination": "192.168.0.0/24", "nexthop": "192.168.0.1"},
]
:param string ipv6_ra_mode: IPv6 Router Advertisement mode. Valid
values are: 'dhcpv6-stateful', 'dhcpv6-stateless', or 'slaac'.
:param string ipv6_address_mode: IPv6 address mode. Valid values are:
'dhcpv6-stateful', 'dhcpv6-stateless', or 'slaac'.
:param string prefixlen: The prefix length to use for subnet allocation
from a subnetpool.
:param bool use_default_subnetpool: Use the default subnetpool for
``ip_version`` to obtain a CIDR. Only one of ``cidr``,
``use_default_subnetpool`` and ``subnetpool_name_or_id`` may be
specified at the same time.
:param string subnetpool_name_or_id: The unique name or id of the
subnetpool to obtain a CIDR from. Only one of ``cidr``,
``use_default_subnetpool`` and ``subnetpool_name_or_id`` may be
specified at the same time.
:param kwargs: Key value pairs to be passed to the Neutron API.
:returns: The created network ``Subnet`` object.
:raises: :class:`~openstack.exceptions.SDKException` on operation
error.
"""
if tenant_id is not None:
filters = {'tenant_id': tenant_id}
else:
filters = None
network = self.get_network(network_name_or_id, filters)
if not network:
raise exceptions.SDKException(
f"Network {network_name_or_id} not found."
)
if disable_gateway_ip and gateway_ip:
raise exceptions.SDKException(
'arg:disable_gateway_ip is not allowed with arg:gateway_ip'
)
uses_subnetpool = use_default_subnetpool or subnetpool_name_or_id
if not cidr and not uses_subnetpool:
raise exceptions.SDKException(
'arg:cidr is required when a subnetpool is not used'
)
if cidr and uses_subnetpool:
raise exceptions.SDKException(
'arg:cidr and subnetpool may not be used at the same time'
)
if use_default_subnetpool and subnetpool_name_or_id:
raise exceptions.SDKException(
'arg:use_default_subnetpool and arg:subnetpool_id may not be '
'used at the same time'
)
subnetpool = None
if subnetpool_name_or_id:
subnetpool = self.get_subnetpool(subnetpool_name_or_id)
if not subnetpool:
raise exceptions.SDKException(
f"Subnetpool {subnetpool_name_or_id} not found."
)
# Be friendly on ip_version and allow strings
if isinstance(ip_version, str):
try:
ip_version = int(ip_version)
except ValueError:
raise exceptions.SDKException('ip_version must be an integer')
# The body of the neutron message for the subnet we wish to create.
# This includes attributes that are required or have defaults.
subnet = dict(
{
'network_id': network['id'],
'ip_version': ip_version,
'enable_dhcp': enable_dhcp,
},
**kwargs,
)
# Add optional attributes to the message.
if cidr:
subnet['cidr'] = cidr
if subnet_name:
subnet['name'] = subnet_name
if tenant_id:
subnet['tenant_id'] = tenant_id
if allocation_pools:
subnet['allocation_pools'] = allocation_pools
if gateway_ip:
subnet['gateway_ip'] = gateway_ip
if disable_gateway_ip:
subnet['gateway_ip'] = None
if dns_nameservers:
subnet['dns_nameservers'] = dns_nameservers
if host_routes:
subnet['host_routes'] = host_routes
if ipv6_ra_mode:
subnet['ipv6_ra_mode'] = ipv6_ra_mode
if ipv6_address_mode:
subnet['ipv6_address_mode'] = ipv6_address_mode
if prefixlen:
subnet['prefixlen'] = prefixlen
if use_default_subnetpool:
subnet['use_default_subnetpool'] = True
if subnetpool:
subnet['subnetpool_id'] = subnetpool["id"]
return self.network.create_subnet(**subnet)
def delete_subnet(self, name_or_id):
"""Delete a subnet.
If a name, instead of a unique UUID, is supplied, it is possible
that we could find more than one matching subnet since names are
not required to be unique. An error will be raised in this case.
:param name_or_id: Name or ID of the subnet being deleted.
:returns: True if delete succeeded, False otherwise.
:raises: :class:`~openstack.exceptions.SDKException` on operation
error.
"""
subnet = self.network.find_subnet(name_or_id, ignore_missing=True)
if not subnet:
self.log.debug("Subnet %s not found for deleting", name_or_id)
return False
self.network.delete_subnet(subnet)
return True
def update_subnet(
self,
name_or_id,
subnet_name=None,
enable_dhcp=None,
gateway_ip=None,
disable_gateway_ip=None,
allocation_pools=None,
dns_nameservers=None,
host_routes=None,
):
"""Update an existing subnet.
:param string name_or_id: Name or ID of the subnet to update.
:param string subnet_name: The new name of the subnet.
:param bool enable_dhcp: Set to ``True`` if DHCP is enabled and
``False`` if disabled.
:param string gateway_ip: The gateway IP address. When you specify both
allocation_pools and gateway_ip, you must ensure that the gateway
IP does not overlap with the specified allocation pools.
:param bool disable_gateway_ip: Set to ``True`` if gateway IP address
is disabled and ``False`` if enabled. It is not allowed with
gateway_ip. Default is ``False``.
:param allocation_pools: A list of dictionaries of the start and end
addresses for the allocation pools. For example::
[{"start": "192.168.199.2", "end": "192.168.199.254"}]
:param dns_nameservers: A list of DNS name servers for the subnet. For
example::
["8.8.8.7", "8.8.8.8"]
:param host_routes: A list of host route dictionaries for the subnet.
For example::
[
{"destination": "0.0.0.0/0", "nexthop": "123.456.78.9"},
{"destination": "192.168.0.0/24", "nexthop": "192.168.0.1"},
]
:returns: The updated network ``Subnet`` object.
:raises: :class:`~openstack.exceptions.SDKException` on operation
error.
"""
subnet = {}
if subnet_name:
subnet['name'] = subnet_name
if enable_dhcp is not None:
subnet['enable_dhcp'] = enable_dhcp
if gateway_ip:
subnet['gateway_ip'] = gateway_ip
if disable_gateway_ip:
subnet['gateway_ip'] = None
if allocation_pools:
subnet['allocation_pools'] = allocation_pools
if dns_nameservers:
subnet['dns_nameservers'] = dns_nameservers
if host_routes:
subnet['host_routes'] = host_routes
if not subnet:
self.log.debug("No subnet data to update")
return
if disable_gateway_ip and gateway_ip:
raise exceptions.SDKException(
'arg:disable_gateway_ip is not allowed with arg:gateway_ip'
)
curr_subnet = self.get_subnet(name_or_id)
if not curr_subnet:
raise exceptions.SDKException(f"Subnet {name_or_id} not found.")
return self.network.update_subnet(curr_subnet, **subnet)
@_utils.valid_kwargs(
'name',
'admin_state_up',
'mac_address',
'fixed_ips',
'subnet_id',
'ip_address',
'security_groups',
'allowed_address_pairs',
'extra_dhcp_opts',
'device_owner',
'device_id',
'binding:vnic_type',
'binding:profile',
'port_security_enabled',
'qos_policy_id',
'binding:host_id',
'project_id',
'description',
'dns_domain',
'dns_name',
'numa_affinity_policy',
'propagate_uplink_status',
'mac_learning_enabled',
)
def create_port(self, network_id, **kwargs):
"""Create a port
:param network_id: The ID of the network. (Required)
:param name: A symbolic name for the port. (Optional)
:param admin_state_up: The administrative status of the port,
which is up (true, default) or down (false). (Optional)
:param mac_address: The MAC address. (Optional)
:param fixed_ips: List of ip_addresses and subnet_ids. See subnet_id
and ip_address. (Optional) For example::
[
{
"ip_address": "10.29.29.13",
"subnet_id": "a78484c4-c380-4b47-85aa-21c51a2d8cbd",
},
...,
]
:param subnet_id: If you specify only a subnet ID, OpenStack Networking
allocates an available IP from that subnet to the port. (Optional)
If you specify both a subnet ID and an IP address, OpenStack
Networking tries to allocate the specified address to the port.
:param ip_address: If you specify both a subnet ID and an IP address,
OpenStack Networking tries to allocate the specified address to
the port.
:param security_groups: List of security group UUIDs. (Optional)
:param allowed_address_pairs: Allowed address pairs list (Optional)
For example::
[
{
"ip_address": "23.23.23.1",
"mac_address": "fa:16:3e:c4:cd:3f",
},
...,
]
:param extra_dhcp_opts: Extra DHCP options. (Optional).
For example::
[{"opt_name": "opt name1", "opt_value": "value1"}, ...]
:param device_owner: The ID of the entity that uses this port.
For example, a DHCP agent. (Optional)
:param device_id: The ID of the device that uses this port.
For example, a virtual server. (Optional)
:param binding vnic_type: The type of the created port. (Optional)
:param port_security_enabled: The security port state created on
the network. (Optional)
:param qos_policy_id: The ID of the QoS policy to apply for
port. (Optional)
:param project_id: The project in which to create the port. (Optional)
:param description: Description of the port. (Optional)
:param dns_domain: DNS domain relevant for the port. (Optional)
:param dns_name: DNS name of the port. (Optional)
:param numa_affinity_policy: the numa affinitiy policy. May be
"None", "required", "preferred" or "legacy". (Optional)
:param propagate_uplink_status: If the uplink status of the port should
be propagated. (Optional)
:param mac_learning_enabled: If mac learning should be enabled on the
port. (Optional)
:returns: The created network ``Port`` object.
:raises: :class:`~openstack.exceptions.SDKException` on operation
error.
"""
kwargs['network_id'] = network_id
return self.network.create_port(**kwargs)
@_utils.valid_kwargs(
'name',
'admin_state_up',
'fixed_ips',
'security_groups',
'allowed_address_pairs',
'extra_dhcp_opts',
'device_owner',
'device_id',
'binding:vnic_type',
'binding:profile',
'port_security_enabled',
'qos_policy_id',
'binding:host_id',
)
def update_port(self, name_or_id, **kwargs):
"""Update a port
Note: to unset an attribute use None value. To leave an attribute
untouched just omit it.
:param name_or_id: name or ID of the port to update. (Required)
:param name: A symbolic name for the port. (Optional)
:param admin_state_up: The administrative status of the port,
which is up (true) or down (false). (Optional)
:param fixed_ips: List of ip_addresses and subnet_ids. (Optional)
If you specify only a subnet ID, OpenStack Networking allocates
an available IP from that subnet to the port.
If you specify both a subnet ID and an IP address, OpenStack
Networking tries to allocate the specified address to the port.
For example::
[
{
"ip_address": "10.29.29.13",
"subnet_id": "a78484c4-c380-4b47-85aa-21c51a2d8cbd",
},
...,
]
:param security_groups: List of security group UUIDs. (Optional)
:param allowed_address_pairs: Allowed address pairs list (Optional)
For example::
[
{
"ip_address": "23.23.23.1",
"mac_address": "fa:16:3e:c4:cd:3f",
},
...,
]
:param extra_dhcp_opts: Extra DHCP options. (Optional).
For example::
[{"opt_name": "opt name1", "opt_value": "value1"}, ...]
:param device_owner: The ID of the entity that uses this port.
For example, a DHCP agent. (Optional)
:param device_id: The ID of the resource this port is attached to.
:param binding vnic_type: The type of the created port. (Optional)
:param port_security_enabled: The security port state created on
the network. (Optional)
:param qos_policy_id: The ID of the QoS policy to apply for port.
:returns: The updated network ``Port`` object.
:raises: :class:`~openstack.exceptions.SDKException` on operation
error.
"""
port = self.get_port(name_or_id=name_or_id)
if port is None:
raise exceptions.SDKException(
f"failed to find port '{name_or_id}'"
)
return self.network.update_port(port, **kwargs)
def delete_port(self, name_or_id):
"""Delete a port
:param name_or_id: ID or name of the port to delete.
:returns: True if delete succeeded, False otherwise.
:raises: :class:`~openstack.exceptions.SDKException` on operation
error.
"""
port = self.network.find_port(name_or_id, ignore_missing=True)
if port is None:
self.log.debug("Port %s not found for deleting", name_or_id)
return False
self.network.delete_port(port)
return True
def _get_port_ids(self, name_or_id_list, filters=None):
"""
Takes a list of port names or ids, retrieves ports and returns a list
with port ids only.
:param list[str] name_or_id_list: list of port names or ids
:param dict filters: optional filters
:raises: SDKException on multiple matches
:raises: NotFoundException if a port is not found
:return: list of port ids
:rtype: list[str]
"""
ids_list = []
for name_or_id in name_or_id_list:
port = self.get_port(name_or_id, filters)
if not port:
raise exceptions.NotFoundException(
f'Port {name_or_id} not found'
)
ids_list.append(port['id'])
return ids_list
def _build_external_gateway_info(
self, ext_gateway_net_id, enable_snat, ext_fixed_ips
):
info = {}
if ext_gateway_net_id:
info['network_id'] = ext_gateway_net_id
# Only send enable_snat if it is explicitly set.
if enable_snat is not None:
info['enable_snat'] = enable_snat
if ext_fixed_ips:
info['external_fixed_ips'] = ext_fixed_ips
if info:
return info
return None
|