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 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529
|
package network
import (
"bytes"
"context"
"database/sql"
"errors"
"fmt"
"maps"
"math/big"
"net"
"net/http"
"net/netip"
"os"
"slices"
"sort"
"strconv"
"strings"
"time"
"github.com/flosch/pongo2"
"github.com/mdlayher/netx/eui64"
ovsClient "github.com/ovn-org/libovsdb/client"
ovsdbModel "github.com/ovn-org/libovsdb/model"
incus "github.com/lxc/incus/v6/client"
"github.com/lxc/incus/v6/internal/iprange"
"github.com/lxc/incus/v6/internal/server/cluster"
"github.com/lxc/incus/v6/internal/server/cluster/request"
"github.com/lxc/incus/v6/internal/server/db"
dbCluster "github.com/lxc/incus/v6/internal/server/db/cluster"
deviceConfig "github.com/lxc/incus/v6/internal/server/device/config"
"github.com/lxc/incus/v6/internal/server/dnsmasq/dhcpalloc"
"github.com/lxc/incus/v6/internal/server/instance"
"github.com/lxc/incus/v6/internal/server/ip"
"github.com/lxc/incus/v6/internal/server/locking"
"github.com/lxc/incus/v6/internal/server/network/acl"
networkOVN "github.com/lxc/incus/v6/internal/server/network/ovn"
ovnSB "github.com/lxc/incus/v6/internal/server/network/ovn/schema/ovn-sb"
"github.com/lxc/incus/v6/internal/server/network/ovs"
"github.com/lxc/incus/v6/internal/server/project"
"github.com/lxc/incus/v6/internal/server/state"
localUtil "github.com/lxc/incus/v6/internal/server/util"
internalUtil "github.com/lxc/incus/v6/internal/util"
"github.com/lxc/incus/v6/shared/api"
"github.com/lxc/incus/v6/shared/logger"
"github.com/lxc/incus/v6/shared/revert"
"github.com/lxc/incus/v6/shared/util"
"github.com/lxc/incus/v6/shared/validate"
)
const (
ovnChassisPriorityMax = 32767
ovnVolatileUplinkIPv4 = "volatile.network.ipv4.address"
ovnVolatileUplinkIPv6 = "volatile.network.ipv6.address"
)
const (
ovnRouterPolicyPeerAllowPriority = 600
ovnRouterPolicyPeerDropPriority = 500
)
// ovnUplinkVars OVN object variables derived from uplink network.
type ovnUplinkVars struct {
// Router.
routerExtPortIPv4Net string
routerExtPortIPv6Net string
routerExtGwIPv4 net.IP
routerExtGwIPv6 net.IP
// External Switch.
extSwitchProviderName string
// DNS.
dnsIPv6 []net.IP
dnsIPv4 []net.IP
}
// ovnUplinkPortBridgeVars uplink bridge port variables used for start/stop.
type ovnUplinkPortBridgeVars struct {
ovsBridge string
uplinkEnd string
ovsEnd string
}
// OVNInstanceNICSetupOpts options for starting an OVN Instance NIC.
type OVNInstanceNICSetupOpts struct {
InstanceUUID string
DeviceName string
DeviceConfig deviceConfig.Device
UplinkConfig map[string]string
DNSName string
LastStateIPs []net.IP
}
// OVNInstanceNICStopOpts options for stopping an OVN Instance NIC.
type OVNInstanceNICStopOpts struct {
InstanceUUID string
DeviceName string
DeviceConfig deviceConfig.Device
}
// ovn represents an OVN network.
type ovn struct {
common
ovnnb *networkOVN.NB
ovnsb *networkOVN.SB
}
func (n *ovn) init(s *state.State, id int64, projectName string, netInfo *api.Network, netNodes map[int64]db.NetworkNode) error {
// Check that OVN is available.
if s != nil {
ovnnb, ovnsb, err := s.OVN()
if err != nil {
return err
}
n.ovnnb = ovnnb
n.ovnsb = ovnsb
}
return n.common.init(s, id, projectName, netInfo, netNodes)
}
// DBType returns the network type DB ID.
func (n *ovn) DBType() db.NetworkType {
return db.NetworkTypeOVN
}
// Config returns the network driver info.
func (n *ovn) Info() Info {
info := n.common.Info()
info.Projects = true
info.NodeSpecificConfig = false
info.AddressForwards = true
info.LoadBalancers = true
info.Peering = true
return info
}
func (n *ovn) State() (*api.NetworkState, error) {
// Get the addresses.
var addresses []api.NetworkStateAddress
IPv4Net, err := ParseIPCIDRToNet(n.config["ipv4.address"])
if err == nil {
ones, _ := IPv4Net.Mask.Size()
addresses = append(addresses, api.NetworkStateAddress{
Family: "inet",
Address: IPv4Net.IP.String(),
Netmask: strconv.Itoa(ones),
Scope: "link",
})
}
IPv6Net, err := ParseIPCIDRToNet(n.config["ipv6.address"])
if err == nil {
ones, _ := IPv6Net.Mask.Size()
addresses = append(addresses, api.NetworkStateAddress{
Family: "inet6",
Address: IPv6Net.IP.String(),
Netmask: strconv.Itoa(ones),
Scope: "link",
})
}
var chassis string
var hwaddr string
var uplinkIPv4 string
var uplinkIPv6 string
logicalRouterName := n.getRouterName()
logicalSwitchName := n.getIntSwitchName()
// Check if an uplink network is present.
if n.config["network"] != "none" {
// Get the current active chassis.
chassis, err = n.ovnsb.GetLogicalRouterPortActiveChassisHostname(context.TODO(), n.getRouterExtPortName())
if err != nil {
return nil, err
}
// Get the IPv4 and IPv6 addresses on the uplink.
if n.config[ovnVolatileUplinkIPv4] != "" {
uplinkIPv4 = n.config[ovnVolatileUplinkIPv4]
}
if n.config[ovnVolatileUplinkIPv6] != "" {
uplinkIPv6 = n.config[ovnVolatileUplinkIPv6]
}
} else if n.config["ipv4.address"] == "none" && n.config["ipv6.address"] == "none" {
// Networks with no uplink and no IP addresses will not have a router.
logicalRouterName = ""
}
// Add the gateway MAC address if one is present.
if logicalRouterName != "" {
var ok bool
hwaddr, ok = n.config["bridge.hwaddr"]
if !ok {
hwaddr, err = n.ovnnb.GetLogicalRouterPortHardwareAddress(context.TODO(), n.getRouterIntPortName())
if err != nil {
return nil, err
}
}
}
// Get the switch MTU.
mtu := int(n.getBridgeMTU())
if mtu == 0 {
mtu = 1500
}
return &api.NetworkState{
Addresses: addresses,
Hwaddr: hwaddr,
Mtu: mtu,
State: "up",
Type: "broadcast",
OVN: &api.NetworkStateOVN{
Chassis: chassis,
LogicalRouter: string(logicalRouterName),
LogicalSwitch: string(logicalSwitchName),
UplinkIPv4: uplinkIPv4,
UplinkIPv6: uplinkIPv6,
},
}, nil
}
// uplinkRoutes parses ipv4.routes and ipv6.routes settings for an uplink network into a slice of *net.IPNet.
func (n *ovn) uplinkRoutes(uplink *api.Network) ([]*net.IPNet, error) {
var err error
var uplinkRoutes []*net.IPNet
for _, k := range []string{"ipv4.routes", "ipv6.routes"} {
if uplink.Config[k] == "" {
continue
}
uplinkRoutes, err = SubnetParseAppend(uplinkRoutes, util.SplitNTrimSpace(uplink.Config[k], ",", -1, false)...)
if err != nil {
return nil, err
}
}
return uplinkRoutes, nil
}
// projectRestrictedSubnets parses the restrict.networks.subnets project setting and returns slice of *net.IPNet.
// Returns nil slice if no project restrictions, or empty slice if no allowed subnets.
func (n *ovn) projectRestrictedSubnets(p *api.Project, uplinkNetworkName string) ([]*net.IPNet, error) {
// Parse project's restricted subnets.
var projectRestrictedSubnets []*net.IPNet // Nil value indicates not restricted.
if util.IsTrue(p.Config["restricted"]) && p.Config["restricted.networks.subnets"] != "" {
projectRestrictedSubnets = []*net.IPNet{} // Empty slice indicates no allowed subnets.
for _, subnetRaw := range util.SplitNTrimSpace(p.Config["restricted.networks.subnets"], ",", -1, false) {
subnetParts := strings.SplitN(subnetRaw, ":", 2)
if len(subnetParts) != 2 {
return nil, fmt.Errorf(`Project subnet %q invalid, must be in the format of "<uplink network>:<subnet>"`, subnetRaw)
}
subnetUplinkName := subnetParts[0]
subnetStr := subnetParts[1]
if subnetUplinkName != uplinkNetworkName {
continue // Only include subnets for our uplink.
}
_, restrictedSubnet, err := net.ParseCIDR(subnetStr)
if err != nil {
return nil, err
}
projectRestrictedSubnets = append(projectRestrictedSubnets, restrictedSubnet)
}
}
return projectRestrictedSubnets, nil
}
// validateExternalSubnet checks the supplied ipNet is allowed within the uplink routes and project
// restricted subnets. If projectRestrictedSubnets is nil, then it is not checked as this indicates project has
// no restrictions. Whereas if uplinkRoutes is nil/empty then this will always return an error.
func (n *ovn) validateExternalSubnet(uplink *api.Network, projectRestrictedSubnets []*net.IPNet, ipNet *net.IPNet) error {
// Check that the IP network is within the project's restricted subnets if restricted.
if projectRestrictedSubnets != nil {
foundMatch := false
for _, projectRestrictedSubnet := range projectRestrictedSubnets {
if SubnetContains(projectRestrictedSubnet, ipNet) {
foundMatch = true
break
}
}
if !foundMatch {
return fmt.Errorf("Project doesn't contain %q in its restricted uplink subnets", ipNet.String())
}
}
// Check if the IP network is within the uplink network's routes.
uplinkRoutes, err := n.uplinkRoutes(uplink)
if err != nil {
return err
}
for _, uplinkRoute := range uplinkRoutes {
if SubnetContains(uplinkRoute, ipNet) {
return nil
}
}
// Load uplink network details.
uplinkIPv4CIDR := uplink.Config["ipv4.address"]
if uplinkIPv4CIDR == "" {
uplinkIPv4CIDR = uplink.Config["ipv4.gateway"]
}
uplinkIPv6CIDR := uplink.Config["ipv6.address"]
if uplinkIPv6CIDR == "" {
uplinkIPv6CIDR = uplink.Config["ipv6.gateway"]
}
uplinkIPv4, uplinkIPv4Net, _ := net.ParseCIDR(uplinkIPv4CIDR)
uplinkIPv6, uplinkIPv6Net, _ := net.ParseCIDR(uplinkIPv6CIDR)
// Check if the IP network is within the uplink network.
if uplinkIPv4Net != nil && SubnetContains(uplinkIPv4Net, ipNet) {
if ipNet.Contains(uplinkIPv4) {
return api.StatusErrorf(http.StatusBadRequest, "Requested subnet %q would mask the uplink gateway", ipNet.String())
}
return nil
}
if uplinkIPv6Net != nil && SubnetContains(uplinkIPv6Net, ipNet) {
if ipNet.Contains(uplinkIPv6) {
return api.StatusErrorf(http.StatusBadRequest, "Requested subnet %q would mask the uplink gateway", ipNet.String())
}
return nil
}
return api.StatusErrorf(http.StatusBadRequest, "Uplink network doesn't contain %q in its routes", ipNet.String())
}
// getExternalSubnetInUse returns information about usage of external subnets by networks and NICs connected to,
// or used by, the specified uplinkNetworkName.
func (n *ovn) getExternalSubnetInUse(uplinkNetworkName string) ([]externalSubnetUsage, error) {
var err error
var projectNetworks map[string]map[int64]api.Network
var externalSubnets []externalSubnetUsage
err = n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
// Get all managed networks across all projects.
projectNetworks, err = tx.GetCreatedNetworks(ctx)
if err != nil {
return fmt.Errorf("Failed to load all networks: %w", err)
}
externalSubnets, err = n.common.getExternalSubnetInUse(ctx, tx, uplinkNetworkName, false)
if err != nil {
return fmt.Errorf("Failed getting external subnets in use: %w", err)
}
return nil
})
if err != nil {
return nil, err
}
// Get OVN networks that use the same uplink as us.
ovnProjectNetworksWithOurUplink := n.ovnProjectNetworksWithUplink(uplinkNetworkName, projectNetworks)
// Get external subnets used by other OVN networks using our uplink.
ovnNetworkExternalSubnets, err := n.ovnNetworkExternalSubnets(ovnProjectNetworksWithOurUplink)
if err != nil {
return nil, err
}
// Get external routes configured on OVN NICs using networks that use our uplink.
ovnNICExternalRoutes, err := n.ovnNICExternalRoutes(ovnProjectNetworksWithOurUplink)
if err != nil {
return nil, err
}
externalSubnets = append(externalSubnets, ovnNetworkExternalSubnets...)
externalSubnets = append(externalSubnets, ovnNICExternalRoutes...)
return externalSubnets, nil
}
// Validate network config.
func (n *ovn) Validate(config map[string]string, clientType request.ClientType) error {
rules := map[string]func(value string) error{
// gendoc:generate(entity=network_ovn, group=common, key=network)
//
// ---
// type: string
// shortdesc: Uplink network to use for external network access or `none` to keep isolated
"network": validate.IsAny,
// gendoc:generate(entity=network_ovn, group=common, key=bridge.hwaddr)
//
// ---
// type: string
// shortdesc: MAC address for the virtual bridge interface
"bridge.hwaddr": validate.Optional(validate.IsNetworkMAC),
// gendoc:generate(entity=network_ovn, group=common, key=bridge.mtu)
//
// ---
// type: integer
// shortdesc: Bridge MTU (default allows host to host Geneve tunnels)
// default: `1442`
"bridge.mtu": validate.Optional(validate.IsNetworkMTU),
// gendoc:generate(entity=network_ovn, group=common, key=bridge.external_interfaces)
//
// ---
// type: string
// shortdesc: Comma-separated list of unconfigured network interfaces to include in the bridge
"bridge.external_interfaces": validate.Optional(validateExternalInterfaces),
// gendoc:generate(entity=network_ovn, group=common, key=ipv4.address)
//
// ---
// type: string
// shortdesc: IPv4 address for the bridge (use `none` to turn off IPv4 or `auto` to generate a new random unused subnet) (CIDR)
// condition: standard mode
// default: (initial value on creation: `auto`)
"ipv4.address": validate.Optional(func(value string) error {
if validate.IsOneOf("none", "auto")(value) == nil {
return nil
}
return validate.IsNetworkAddressCIDRV4(value)
}),
// gendoc:generate(entity=network_ovn, group=common, key=ipv4.dhcp)
//
// ---
// type: bool
// shortdesc: Whether to allocate addresses using DHCP
// condition: IPv4 address
// default: `true`
"ipv4.dhcp": validate.Optional(validate.IsBool),
// gendoc:generate(entity=network_ovn, group=common, key=ipv4.dhcp.expiry)
//
// ---
// type: string
// shortdesc: When to expire DHCP leases
// condition: IPv4 DHCP
// default: `1h`
"ipv4.dhcp.expiry": validate.Optional(func(value string) error {
_, err := time.ParseDuration(value)
return err
}),
// gendoc:generate(entity=network_ovn, group=common, key=ipv4.dhcp.ranges)
//
// ---
// type: string
// condition: IPv4 DHCP
// default: all addresses
// shortdesc: Comma-separated list of IP ranges to use for DHCP (FIRST-LAST format)
"ipv4.dhcp.ranges": validate.Optional(validate.IsListOf(validate.IsNetworkRangeV4)),
// gendoc:generate(entity=network_ovn, group=common, key=ipv4.dhcp.routes)
//
// ---
// type: string
// condition: IPv4 DHCP
// shortdesc: Static routes to provide via DHCP option 121, as a comma-separated list of alternating subnets (CIDR) and gateway addresses (same syntax as dnsmasq and OVN)
"ipv4.dhcp.routes": validate.Optional(validate.IsDHCPRouteList),
// gendoc:generate(entity=network_ovn, group=common, key=ipv6.address)
//
// ---
// type: string
// shortdesc: IPv6 address for the bridge (use `none` to turn off IPv6 or `auto` to generate a new random unused subnet) (CIDR)
// condition: standard mode
// default: (initial value on creation: `auto`)
"ipv6.address": validate.Optional(func(value string) error {
if validate.IsOneOf("none", "auto")(value) == nil {
return nil
}
return validate.IsNetworkAddressCIDRV6(value)
}),
// gendoc:generate(entity=network_ovn, group=common, key=ipv6.dhcp)
//
// ---
// type: bool
// condition: IPv6 address
// shortdesc: Whether to provide additional network configuration over DHCP
// default: `true`
"ipv6.dhcp": validate.Optional(validate.IsBool),
// gendoc:generate(entity=network_ovn, group=common, key=ipv6.dhcp.stateful)
//
// ---
// type: bool
// condition: IPv6 DHCP
// shortdesc: Whether to allocate addresses using DHCP
// default: `false`
"ipv6.dhcp.stateful": validate.Optional(validate.IsBool),
// gendoc:generate(entity=network_ovn, group=common, key=ipv4.nat)
//
// ---
// type: bool
// shortdesc: Whether to NAT
// condition: IPv4 address
// default: `false` initial value on creation if `ipv4.address` is set to `auto: true`)
"ipv4.nat": validate.Optional(validate.IsBool),
// gendoc:generate(entity=network_ovn, group=common, key=ipv4.nat.address)
//
// ---
// type: string
// shortdesc: The source address used for outbound traffic from the network (requires uplink `ovn.ingress_mode=routed`)
// condition: IPv4 address
"ipv4.nat.address": validate.Optional(validate.IsNetworkAddressV4),
// gendoc:generate(entity=network_ovn, group=common, key=ipv6.nat)
//
// ---
// type: bool
// condition: IPv6 address
// shortdesc: Whether to NAT
// default: `false` (initial value on creation if `ipv6.address` is set to `auto: true`)
"ipv6.nat": validate.Optional(validate.IsBool),
// gendoc:generate(entity=network_ovn, group=common, key=ipv6.nat.address)
//
// ---
// type: string
// condition: IPv6 address
// shortdesc: The source address used for outbound traffic from the network (requires uplink `ovn.ingress_mode=routed`)
"ipv6.nat.address": validate.Optional(validate.IsNetworkAddressV6),
// gendoc:generate(entity=network_ovn, group=common, key=ipv4.l3only)
//
// ---
// type: bool
// shortdesc: Whether to enable layer 3 only mode.
// condition: IPv4 address
// default: `false`
"ipv4.l3only": validate.Optional(validate.IsBool),
// gendoc:generate(entity=network_ovn, group=common, key=ipv6.l3only)
//
// ---
// type: bool
// condition: IPv6 DHCP stateful
// shortdesc: Whether to enable layer 3 only mode.
// default: `false`
"ipv6.l3only": validate.Optional(validate.IsBool),
// gendoc:generate(entity=network_ovn, group=common, key=dns.nameservers)
//
// ---
// type: string
// shortdesc: DNS server IPs to advertise to DHCP clients and via Router Advertisements. Both IPv4 and IPv6 addresses get pushed via DHCP, and the first IPv6 address is also advertised as RDNSS via RA.
// default: Uplink DNS servers (IPv4 and IPv6 address if no uplink is configured)
"dns.nameservers": validate.Optional(validate.IsListOf(validate.IsNetworkAddress)),
// gendoc:generate(entity=network_ovn, group=common, key=dns.domain)
//
// ---
// type: string
// default: `incus`
// shortdesc: Domain to advertise to DHCP clients and use for DNS resolution
"dns.domain": validate.IsAny,
// gendoc:generate(entity=network_ovn, group=common, key=dns.search)
//
// ---
// type: string
// shortdesc: Full comma-separated domain search list, defaulting to `dns.domain` value
"dns.search": validate.IsAny,
// gendoc:generate(entity=network_ovn, group=common, key=dns.zone.forward)
//
// ---
// type: string
// shortdesc: Comma-separated list of DNS zone names for forward DNS records
"dns.zone.forward": validate.IsAny,
// gendoc:generate(entity=network_ovn, group=common, key=dns.zone.reverse.ipv4)
//
// ---
// type: string
// shortdesc: DNS zone name for IPv4 reverse DNS records
"dns.zone.reverse.ipv4": validate.IsAny,
// gendoc:generate(entity=network_ovn, group=common, key=dns.zone.reverse.ipv6)
//
// ---
// type: string
// shortdesc: DNS zone name for IPv6 reverse DNS records
"dns.zone.reverse.ipv6": validate.IsAny,
// gendoc:generate(entity=network_ovn, group=common, key=security.acls)
//
// ---
// type: string
// shortdesc: Comma-separated list of Network ACLs to apply to NICs connected to this network
"security.acls": validate.IsAny,
// gendoc:generate(entity=network_ovn, group=common, key=security.acls.default.ingress.action)
//
// ---
// type: string
// condition: `security.acls`
// shortdesc: Action to use for ingress traffic that doesn't match any ACL rule
// default: `reject`
"security.acls.default.ingress.action": validate.Optional(validate.IsOneOf(acl.ValidActions...)),
// gendoc:generate(entity=network_ovn, group=common, key=security.acls.default.egress.action)
//
// ---
// type: string
// shortdesc: Action to use for egress traffic that doesn't match any ACL rule
// default: `reject`
// condition: `security.acls`
"security.acls.default.egress.action": validate.Optional(validate.IsOneOf(acl.ValidActions...)),
// gendoc:generate(entity=network_ovn, group=common, key=security.acls.default.ingress.logged)
//
// ---
// type: bool
// condition: `security.acls`
// shortdesc: Whether to log ingress traffic that doesn't match any ACL rule
// default: `false`
"security.acls.default.ingress.logged": validate.Optional(validate.IsBool),
// gendoc:generate(entity=network_ovn, group=common, key=security.acls.default.egress.logged)
//
// ---
// type: bool
// shortdesc: Whether to log egress traffic that doesn't match any ACL rule
// default: `false`
// condition: `security.acls`
"security.acls.default.egress.logged": validate.Optional(validate.IsBool),
// gendoc:generate(entity=network_ovn, group=common, key=user.*)
//
// ---
// type: string
// shortdesc: User-provided free-form key/value pairs
// Volatile keys populated automatically as needed.
ovnVolatileUplinkIPv4: validate.Optional(validate.IsNetworkAddressV4),
ovnVolatileUplinkIPv6: validate.Optional(validate.IsNetworkAddressV6),
}
err := n.validate(config, rules)
if err != nil {
return err
}
// Perform composite key checks after per-key validation.
// Validate DNS zone names.
err = n.validateZoneNames(config)
if err != nil {
return err
}
if config["ipv4.address"] != "" {
ipv4Addr, ipv4Net, _ := net.ParseCIDR(config["ipv4.address"])
if ipv4Net != nil {
ovnRouter, err := netip.ParseAddr(dhcpalloc.GetIP(ipv4Net, -2).String())
if err != nil {
return err
}
addr, err := netip.ParseAddr(ipv4Addr.String())
if err != nil {
return err
}
if ovnRouter.Compare(addr) == 0 {
return fmt.Errorf("'ipv4.address' cannot be set to %s because it is reserved for OVN load-balancer health checks", ovnRouter.String())
}
}
}
// Check that if IPv6 enabled then the network size must be at least a /64 as both RA and DHCPv6
// in OVN (as it generates addresses using EUI64) require at least a /64 subnet to operate.
_, ipv6Net, _ := net.ParseCIDR(config["ipv6.address"])
if ipv6Net != nil {
ones, _ := ipv6Net.Mask.Size()
if ones > 64 {
return errors.New("IPv6 subnet must be at least a /64")
}
}
// Load the project to get uplink network restrictions.
var p *api.Project
err = n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
project, err := dbCluster.GetProject(ctx, tx.Tx(), n.project)
if err != nil {
return err
}
p, err = project.ToAPI(ctx, tx.Tx())
return err
})
if err != nil {
return fmt.Errorf("Failed to load network restrictions from project %q: %w", n.project, err)
}
// Check uplink network is valid and allowed in project.
var uplink *api.Network
projectRestrictedSubnets := []*net.IPNet{}
if n.config["network"] != "none" && clientType != request.ClientTypeNotifier {
uplinkNetworkName, err := n.validateUplinkNetwork(p, config["network"])
if err != nil {
return err
}
err = n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
// Get uplink routes.
_, uplink, _, err = tx.GetNetworkInAnyState(ctx, api.ProjectDefaultName, uplinkNetworkName)
return err
})
if err != nil {
return fmt.Errorf("Failed to load uplink network %q: %w", uplinkNetworkName, err)
}
// Get project restricted routes.
projectRestrictedSubnets, err = n.projectRestrictedSubnets(p, uplinkNetworkName)
if err != nil {
return err
}
}
// Parse the network's address subnets for further checks.
netSubnets := make(map[string]*net.IPNet)
for _, keyPrefix := range []string{"ipv4", "ipv6"} {
addressKey := fmt.Sprintf("%s.address", keyPrefix)
if validate.IsOneOf("", "none", "auto")(config[addressKey]) != nil {
_, ipNet, err := net.ParseCIDR(config[addressKey])
if err != nil {
return fmt.Errorf("Failed parsing %q: %w", addressKey, err)
}
netSubnets[addressKey] = ipNet
}
}
// Check Security ACLs exist.
if config["security.acls"] != "" {
err = acl.Exists(n.state, n.project, util.SplitNTrimSpace(config["security.acls"], ",", -1, true)...)
if err != nil {
return err
}
}
// Check that ipv6.l3only mode is used with ipvp.dhcp.stateful.
// As otherwise the router advertisements will configure an address using the subnet's mask.
if util.IsTrue(config["ipv6.l3only"]) && util.IsTrueOrEmpty(config["ipv6.dhcp"]) && util.IsFalseOrEmpty(config["ipv6.dhcp.stateful"]) {
return errors.New("The ipv6.dhcp.stateful setting must be enabled when using ipv6.l3only mode with ipv6.dhcp enabled")
}
// All tests below are related to the uplink network, skip if we don't have one.
if uplink == nil {
return nil
}
// If NAT disabled, parse the external subnets that are being requested.
var externalSubnets []*net.IPNet // Subnets to check for conflicts with other networks/NICs.
for _, keyPrefix := range []string{"ipv4", "ipv6"} {
addressKey := fmt.Sprintf("%s.address", keyPrefix)
netSubnet := netSubnets[addressKey]
if util.IsFalseOrEmpty(config[fmt.Sprintf("%s.nat", keyPrefix)]) && netSubnet != nil {
// Add to list to check for conflicts.
externalSubnets = append(externalSubnets, netSubnet)
}
}
// Check SNAT addresses specified are allowed to be used based on uplink's ovn.ingress_mode setting.
var externalSNATSubnets []*net.IPNet // Subnets to check for conflicts with other networks/NICs.
for _, keyPrefix := range []string{"ipv4", "ipv6"} {
snatAddressKey := fmt.Sprintf("%s.nat.address", keyPrefix)
if config[snatAddressKey] != "" {
if uplink.Config["ovn.ingress_mode"] != "routed" {
return fmt.Errorf(`Cannot specify %q when uplink ovn.ingress_mode is not "routed"`, snatAddressKey)
}
subnetSize := 128
if keyPrefix == "ipv4" {
subnetSize = 32
}
_, snatIPNet, err := net.ParseCIDR(fmt.Sprintf("%s/%d", config[snatAddressKey], subnetSize))
if err != nil {
return fmt.Errorf("Failed parsing %q: %w", snatAddressKey, err)
}
// Add to list to check for conflicts.
externalSNATSubnets = append(externalSNATSubnets, snatIPNet)
}
}
if len(externalSubnets) > 0 || len(externalSNATSubnets) > 0 {
externalSubnetsInUse, err := n.getExternalSubnetInUse(config["network"])
if err != nil {
return err
}
// Check if uplink has routed ingress anycast mode enabled, as this relaxes the overlap checks.
ipv4UplinkAnycast := n.uplinkHasIngressRoutedAnycastIPv4(uplink)
ipv6UplinkAnycast := n.uplinkHasIngressRoutedAnycastIPv6(uplink)
for _, externalSubnet := range externalSubnets {
// Check the external subnet is allowed within both the uplink's external routes and any
// project restricted subnets.
err = n.validateExternalSubnet(uplink, projectRestrictedSubnets, externalSubnet)
if err != nil {
return err
}
// Skip overlap checks if external subnet's protocol has anycast mode enabled on uplink.
if externalSubnet.IP.To4() == nil {
if ipv6UplinkAnycast {
continue
}
} else if ipv4UplinkAnycast {
continue
}
// Check the external subnet doesn't fall within any existing OVN network external subnets.
for _, externalSubnetUser := range externalSubnetsInUse {
// Skip our own network (but not NIC devices on our own network).
if externalSubnetUser.usageType != subnetUsageInstance && externalSubnetUser.networkProject == n.project && externalSubnetUser.networkName == n.name {
continue
}
if SubnetContains(&externalSubnetUser.subnet, externalSubnet) || SubnetContains(externalSubnet, &externalSubnetUser.subnet) {
// This error is purposefully vague so that it doesn't reveal any names of
// resources potentially outside of the network's project.
return fmt.Errorf("External subnet %q overlaps with another network or NIC", externalSubnet.String())
}
}
}
for _, externalSNATSubnet := range externalSNATSubnets {
// Check the external subnet is allowed within both the uplink's external routes and any
// project restricted subnets.
err = n.validateExternalSubnet(uplink, projectRestrictedSubnets, externalSNATSubnet)
if err != nil {
return err
}
// Skip overlap checks if external subnet's protocol has anycast mode enabled on uplink.
if externalSNATSubnet.IP.To4() == nil {
if ipv6UplinkAnycast {
continue
}
} else if ipv4UplinkAnycast {
continue
}
// Check the external subnet doesn't fall within any existing OVN network external subnets.
for _, externalSubnetUser := range externalSubnetsInUse {
// Skip our own network (including NIC devices on our own network).
// Because we may want to specify the SNAT address as the same address as one of
// the NICs in our network.
if externalSubnetUser.networkProject == n.project && externalSubnetUser.networkName == n.name {
continue
}
if SubnetContains(&externalSubnetUser.subnet, externalSNATSubnet) || SubnetContains(externalSNATSubnet, &externalSubnetUser.subnet) {
// This error is purposefully vague so that it doesn't reveal any names of
// resources potentially outside of the network's project.
return fmt.Errorf("NAT address %q overlaps with another OVN network or NIC", externalSNATSubnet.IP.String())
}
}
}
}
// Check any existing network forward target addresses are suitable for this network's subnet.
var forwards map[int64]*api.NetworkForward
err = n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
networkID := n.ID()
dbRecords, err := dbCluster.GetNetworkForwards(ctx, tx.Tx(), dbCluster.NetworkForwardFilter{
NetworkID: &networkID,
})
if err != nil {
return err
}
forwards = make(map[int64]*api.NetworkForward)
for _, dbRecord := range dbRecords {
forward, err := dbRecord.ToAPI(ctx, tx.Tx())
if err != nil {
return err
}
forwards[dbRecord.ID] = forward
}
return nil
})
if err != nil {
return fmt.Errorf("Failed loading network forwards: %w", err)
}
for _, forward := range forwards {
if forward.Config["target_address"] != "" {
defaultTargetIP := net.ParseIP(forward.Config["target_address"])
netSubnet := netSubnets["ipv4.address"]
if defaultTargetIP.To4() == nil {
netSubnet = netSubnets["ipv6.address"]
}
if !SubnetContainsIP(netSubnet, defaultTargetIP) {
return api.StatusErrorf(http.StatusBadRequest, "Network forward for %q has a default target address %q that is not within the network subnet", forward.ListenAddress, defaultTargetIP.String())
}
}
for _, port := range forward.Ports {
targetIP := net.ParseIP(port.TargetAddress)
netSubnet := netSubnets["ipv4.address"]
if targetIP.To4() == nil {
netSubnet = netSubnets["ipv6.address"]
}
if !SubnetContainsIP(netSubnet, targetIP) {
return api.StatusErrorf(http.StatusBadRequest, "Network forward for %q has a port target address %q that is not within the network subnet", forward.ListenAddress, targetIP.String())
}
}
}
var dbLoadBalancers []dbCluster.NetworkLoadBalancer
err = n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
networkID := n.ID()
// Get the load balancers.
dbLoadBalancers, err = dbCluster.GetNetworkLoadBalancers(ctx, tx.Tx(), dbCluster.NetworkLoadBalancerFilter{
NetworkID: &networkID,
})
if err != nil {
return err
}
return nil
})
if err != nil {
return fmt.Errorf("Failed loading network load balancers: %w", err)
}
for _, dbLoadBalancer := range dbLoadBalancers {
for _, port := range dbLoadBalancer.Backends {
targetIP := net.ParseIP(port.TargetAddress)
netSubnet := netSubnets["ipv4.address"]
if targetIP.To4() == nil {
netSubnet = netSubnets["ipv6.address"]
}
if !SubnetContainsIP(netSubnet, targetIP) {
return api.StatusErrorf(http.StatusBadRequest, "Network load balancer for %q has a backend target address %q that is not within the network subnet", dbLoadBalancer.ListenAddress, targetIP.String())
}
}
}
return nil
}
// getBridgeMTU returns MTU that should be used for the bridge and instance devices.
// Will also be used to configure the OVN DHCP and IPv6 RA options. Returns 0 if the bridge.mtu is not set/invalid.
func (n *ovn) getBridgeMTU() uint32 {
if n.config["bridge.mtu"] != "" {
mtu, err := strconv.ParseUint(n.config["bridge.mtu"], 10, 32)
if err != nil {
return 0
}
return uint32(mtu)
}
return 0
}
// getUnderlayInfo returns the MTU for the underlay network interface and the enscapsulation IP for OVN tunnels.
func (n *ovn) getUnderlayInfo() (uint32, net.IP, error) {
// findMTUFromIP searches all interfaces on the host looking for one that has specified IP.
findMTUFromIP := func(findIP net.IP) (uint32, error) {
// Look for interface that has the OVN enscapsulation IP assigned.
ifaces, err := net.Interfaces()
if err != nil {
return 0, fmt.Errorf("Failed getting local network interfaces: %w", err)
}
for _, iface := range ifaces {
addrs, err := iface.Addrs()
if err != nil {
continue
}
for _, addr := range addrs {
ip, _, err := net.ParseCIDR(addr.String())
if err != nil {
continue
}
if ip.Equal(findIP) {
underlayMTU, err := GetDevMTU(iface.Name)
if err != nil {
return 0, fmt.Errorf("Failed getting MTU for %q: %w", iface.Name, err)
}
return underlayMTU, nil // Found what we were looking for.
}
}
}
return 0, fmt.Errorf("No matching interface found for OVN enscapsulation IP %q", findIP.String())
}
vswitch, err := n.state.OVS()
if err != nil {
return 0, nil, fmt.Errorf("Failed to connect to OVS: %w", err)
}
encapIP, err := vswitch.GetOVNEncapIP(context.TODO())
if err != nil {
return 0, nil, fmt.Errorf("Failed getting OVN enscapsulation IP from OVS: %w", err)
}
underlayMTU, err := findMTUFromIP(encapIP)
if err != nil {
return 0, nil, err
}
return underlayMTU, encapIP, nil
}
// getOptimalBridgeMTU returns the MTU that can be used for the bridge and instance devices based on the MTU value
// of the OVN underlay network interface. This assumes that the OVN tunnel mechanism used is geneve and that the
// same underlying network settings (MTU and encapsulation IP family) are used on all OVN nodes.
func (n *ovn) getOptimalBridgeMTU() (uint32, error) {
// Get underlay MTU and encapsulation IP.
underlayMTU, encapIP, err := n.getUnderlayInfo()
if err != nil {
return 0, fmt.Errorf("Failed getting OVN underlay info: %w", err)
}
// Encapsulation family is IPv6.
if encapIP.To4() == nil {
// If the underlay's MTU is large enough to accommodate a 1500 overlay MTU and the geneve tunnel
// overhead of 78 bytes (when used with IPv6 encapsulation) then indicate 1500 MTU can be used.
if underlayMTU >= 1578 {
return 1500, nil
}
// Default to 1422 which can work with an underlay MTU of 1500.
return 1422, nil
}
// If the underlay's MTU is large enough to accommodate a 1500 overlay MTU and the geneve tunnel
// overhead of 58 bytes (when used with IPv4 encapsulation) then indicate 1500 MTU can be used.
if underlayMTU >= 1558 {
return 1500, nil
}
// Default to 1442 which can work with underlay MTU of 1500.
return 1442, nil
}
// getNetworkPrefix returns OVN network prefix to use for object names.
func (n *ovn) getNetworkPrefix() string {
return acl.OVNNetworkPrefix(n.id)
}
// getChassisGroup returns OVN chassis group name to use.
func (n *ovn) getChassisGroupName() networkOVN.OVNChassisGroup {
return networkOVN.OVNChassisGroup(n.getNetworkPrefix())
}
// getRouterName returns OVN logical router name to use.
func (n *ovn) getRouterName() networkOVN.OVNRouter {
return networkOVN.OVNRouter(fmt.Sprintf("%s-lr", n.getNetworkPrefix()))
}
// getRouterExtPortName returns OVN logical router external port name to use.
func (n *ovn) getRouterExtPortName() networkOVN.OVNRouterPort {
return networkOVN.OVNRouterPort(fmt.Sprintf("%s-lrp-ext", n.getRouterName()))
}
// getRouterIntPortName returns OVN logical router internal port name to use.
func (n *ovn) getRouterIntPortName() networkOVN.OVNRouterPort {
return networkOVN.OVNRouterPort(fmt.Sprintf("%s-lrp-int", n.getRouterName()))
}
// getRouterMAC returns OVN router MAC address to use for ports. Uses a stable seed to return stable random MAC.
func (n *ovn) getRouterMAC() (net.HardwareAddr, error) {
hwAddr := n.config["bridge.hwaddr"]
if hwAddr == "" {
// Load server certificate. This is needs to be the same certificate for all nodes in a cluster.
cert, err := internalUtil.LoadCert(n.state.OS.VarDir)
if err != nil {
return nil, err
}
// Generate the random seed, this uses the server certificate fingerprint (to ensure that multiple
// standalone nodes on the same external network don't generate the same MAC for their networks).
// It relies on the certificate being the same for all nodes in a cluster to allow the same MAC to
// be generated on each bridge interface in the network.
seed := fmt.Sprintf("%s.%d.%d", cert.Fingerprint(), 0, n.ID())
r, err := localUtil.GetStableRandomGenerator(seed)
if err != nil {
return nil, fmt.Errorf("Failed generating stable random router MAC: %w", err)
}
hwAddr = randomHwaddr(r)
n.logger.Debug("Stable MAC generated", logger.Ctx{"seed": seed, "hwAddr": hwAddr})
}
mac, err := net.ParseMAC(hwAddr)
if err != nil {
return nil, fmt.Errorf("Failed parsing router MAC address %q: %w", mac, err)
}
return mac, nil
}
// getRouterIntPortIPv4Net returns OVN logical router internal port IPv4 address and subnet.
func (n *ovn) getRouterIntPortIPv4Net() string {
return n.config["ipv4.address"]
}
// parseRouterIntPortIPv4Net returns OVN logical router internal port IPv4 address and subnet parsed (if set).
func (n *ovn) parseRouterIntPortIPv4Net() (net.IP, *net.IPNet, error) {
ipNet := n.getRouterIntPortIPv4Net()
if validate.IsOneOf("none", "")(ipNet) != nil {
routerIntPortIPv4, routerIntPortIPv4Net, err := net.ParseCIDR(ipNet)
if err != nil {
return nil, nil, fmt.Errorf("Failed parsing router's internal port IPv4 Net: %w", err)
}
return routerIntPortIPv4, routerIntPortIPv4Net, nil
}
return nil, nil, nil
}
// getRouterIntPortIPv4Net returns OVN logical router internal port IPv6 address and subnet.
func (n *ovn) getRouterIntPortIPv6Net() string {
return n.config["ipv6.address"]
}
// parseRouterIntPortIPv6Net returns OVN logical router internal port IPv6 address and subnet parsed (if set).
func (n *ovn) parseRouterIntPortIPv6Net() (net.IP, *net.IPNet, error) {
ipNet := n.getRouterIntPortIPv6Net()
if validate.IsOneOf("none", "")(ipNet) != nil {
routerIntPortIPv4, routerIntPortIPv4Net, err := net.ParseCIDR(ipNet)
if err != nil {
return nil, nil, fmt.Errorf("Failed parsing router's internal port IPv6 Net: %w", err)
}
return routerIntPortIPv4, routerIntPortIPv4Net, nil
}
return nil, nil, nil
}
// getDomainName returns OVN DHCP domain name.
func (n *ovn) getDomainName() string {
if n.config["dns.domain"] != "" {
return n.config["dns.domain"]
}
return "incus"
}
// getDNSSearchList returns OVN DHCP DNS search list. If no search list set returns getDomainName() as list.
func (n *ovn) getDNSSearchList() []string {
if n.config["dns.search"] != "" {
return util.SplitNTrimSpace(n.config["dns.search"], ",", -1, false)
}
return []string{n.getDomainName()}
}
// getExtSwitchName returns OVN logical external switch name.
func (n *ovn) getExtSwitchName() networkOVN.OVNSwitch {
return networkOVN.OVNSwitch(fmt.Sprintf("%s-ls-ext", n.getNetworkPrefix()))
}
// getExtSwitchRouterPortName returns OVN logical external switch router port name.
func (n *ovn) getExtSwitchRouterPortName() networkOVN.OVNSwitchPort {
return networkOVN.OVNSwitchPort(fmt.Sprintf("%s-lsp-router", n.getExtSwitchName()))
}
// getExtSwitchProviderPortName returns OVN logical external switch provider port name.
func (n *ovn) getExtSwitchProviderPortName() networkOVN.OVNSwitchPort {
return networkOVN.OVNSwitchPort(fmt.Sprintf("%s-lsp-provider", n.getExtSwitchName()))
}
// getIntSwitchName returns OVN logical internal switch name.
func (n *ovn) getIntSwitchName() networkOVN.OVNSwitch {
return acl.OVNIntSwitchName(n.id)
}
// getIntSwitchRouterPortName returns OVN logical internal switch router port name.
func (n *ovn) getIntSwitchRouterPortName() networkOVN.OVNSwitchPort {
return acl.OVNIntSwitchRouterPortName(n.id)
}
// getIntSwitchInstancePortPrefix returns OVN logical internal switch instance port name prefix.
func (n *ovn) getIntSwitchInstancePortPrefix() string {
return fmt.Sprintf("%s-instance", n.getNetworkPrefix())
}
// getLoadBalancerName returns OVN load balancer name to use for a listen address.
func (n *ovn) getLoadBalancerName(listenAddress string) networkOVN.OVNLoadBalancer {
return networkOVN.OVNLoadBalancer(fmt.Sprintf("%s-lb-%s", n.getNetworkPrefix(), listenAddress))
}
// getLogicalRouterPeerPortName returns OVN logical router port name to use for a peer connection.
func (n *ovn) getLogicalRouterPeerPortName(peerNetworkID int64) networkOVN.OVNRouterPort {
return networkOVN.OVNRouterPort(fmt.Sprintf("%s-lrp-peer-net%d", n.getRouterName(), peerNetworkID))
}
// setupUplinkPort initializes the uplink connection. Returns the derived ovnUplinkVars settings used
// during the initial creation of the logical network.
func (n *ovn) setupUplinkPort(routerMAC net.HardwareAddr) (*ovnUplinkVars, error) {
if n.config["network"] == "none" {
return nil, nil
}
// Uplink network must be in default project.
uplinkNet, err := LoadByName(n.state, api.ProjectDefaultName, n.config["network"])
if err != nil {
return nil, fmt.Errorf("Failed loading uplink network %q: %w", n.config["network"], err)
}
switch uplinkNet.Type() {
case "bridge":
return n.setupUplinkPortBridge(uplinkNet, routerMAC)
case "physical":
return n.setupUplinkPortPhysical(uplinkNet, routerMAC)
}
return nil, fmt.Errorf("Failed setting up uplink port, network type %q unsupported as OVN uplink", uplinkNet.Type())
}
// setupUplinkPortBridge allocates external IPs on the uplink bridge.
// Returns the derived ovnUplinkVars settings.
func (n *ovn) setupUplinkPortBridge(uplinkNet Network, routerMAC net.HardwareAddr) (*ovnUplinkVars, error) {
bridgeNet, ok := uplinkNet.(*bridge)
if !ok {
return nil, errors.New("Network is not bridge type")
}
err := bridgeNet.checkClusterWideMACSafe(bridgeNet.config)
if err != nil {
return nil, fmt.Errorf("Network %q is not suitable for use as OVN uplink: %w", bridgeNet.name, err)
}
v, err := n.allocateUplinkPortIPs(uplinkNet, routerMAC)
if err != nil {
return nil, fmt.Errorf("Failed allocating uplink port IPs on network %q: %w", uplinkNet.Name(), err)
}
return v, nil
}
// setupUplinkPortPhysical allocates external IPs on the uplink network.
// Returns the derived ovnUplinkVars settings.
func (n *ovn) setupUplinkPortPhysical(uplinkNet Network, routerMAC net.HardwareAddr) (*ovnUplinkVars, error) {
v, err := n.allocateUplinkPortIPs(uplinkNet, routerMAC)
if err != nil {
return nil, fmt.Errorf("Failed allocating uplink port IPs on network %q: %w", uplinkNet.Name(), err)
}
return v, nil
}
// allocateUplinkPortIPs attempts to find a free IP in the uplink network's OVN ranges and then stores it in
// ovnVolatileUplinkIPv4 and ovnVolatileUplinkIPv6 config keys on this network. Returns ovnUplinkVars settings.
func (n *ovn) allocateUplinkPortIPs(uplinkNet Network, routerMAC net.HardwareAddr) (*ovnUplinkVars, error) {
v := &ovnUplinkVars{}
uplinkNetConf := uplinkNet.Config()
// Uplink derived settings.
v.extSwitchProviderName = uplinkNet.Name()
// Detect uplink gateway setting.
uplinkIPv4CIDR := uplinkNetConf["ipv4.address"]
if uplinkIPv4CIDR == "" {
uplinkIPv4CIDR = uplinkNetConf["ipv4.gateway"]
}
uplinkIPv6CIDR := uplinkNetConf["ipv6.address"]
if uplinkIPv6CIDR == "" {
uplinkIPv6CIDR = uplinkNetConf["ipv6.gateway"]
}
// Optional uplink values.
uplinkIPv4, uplinkIPv4Net, err := net.ParseCIDR(uplinkIPv4CIDR)
if err == nil {
v.dnsIPv4 = []net.IP{uplinkIPv4}
v.routerExtGwIPv4 = uplinkIPv4
}
uplinkIPv6, uplinkIPv6Net, err := net.ParseCIDR(uplinkIPv6CIDR)
if err == nil {
v.dnsIPv6 = []net.IP{uplinkIPv6}
v.routerExtGwIPv6 = uplinkIPv6
}
// Detect optional DNS server list.
if uplinkNetConf["dns.nameservers"] != "" {
// Reset nameservers.
v.dnsIPv4 = nil
v.dnsIPv6 = nil
nsList := util.SplitNTrimSpace(uplinkNetConf["dns.nameservers"], ",", -1, false)
for _, ns := range nsList {
nsIP := net.ParseIP(ns)
if nsIP == nil {
return nil, errors.New("Invalid uplink nameserver")
}
if nsIP.To4() == nil {
v.dnsIPv6 = append(v.dnsIPv6, nsIP)
} else {
v.dnsIPv4 = append(v.dnsIPv4, nsIP)
}
}
}
// Parse existing allocated IPs for this network on the uplink network (if not set yet, will be nil).
routerExtPortIPv4 := net.ParseIP(n.config[ovnVolatileUplinkIPv4])
routerExtPortIPv6 := net.ParseIP(n.config[ovnVolatileUplinkIPv6])
// Check if uplink is viable at all.
if uplinkIPv4Net == nil && uplinkIPv6Net == nil {
return nil, errors.New("Uplink network doesn't have IPv4 or IPv6 configured")
}
// Decide whether we need to allocate new IP(s) and go to the expense of retrieving all allocated IPs.
if (uplinkIPv4Net != nil && routerExtPortIPv4 == nil) || (uplinkIPv6Net != nil && routerExtPortIPv6 == nil) {
err := n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
allAllocatedIPv4, allAllocatedIPv6, err := n.uplinkAllAllocatedIPs(ctx, tx, uplinkNet.Name())
if err != nil {
return fmt.Errorf("Failed to get all allocated IPs for uplink: %w", err)
}
if uplinkIPv4Net != nil && routerExtPortIPv4 == nil {
if uplinkNetConf["ipv4.ovn.ranges"] == "" {
return errors.New(`Missing required "ipv4.ovn.ranges" config key on uplink network`)
}
dhcpSubnet := uplinkNet.DHCPv4Subnet()
allowedNets := []*net.IPNet{}
if dhcpSubnet != nil {
allowedNets = append(allowedNets, dhcpSubnet)
} else {
allowedNets = append(allowedNets, uplinkIPv4Net)
}
ipRanges, err := parseIPRanges(uplinkNetConf["ipv4.ovn.ranges"], allowedNets...)
if err != nil {
return fmt.Errorf("Failed to parse uplink IPv4 OVN ranges: %w", err)
}
routerExtPortIPv4, err = n.uplinkAllocateIP(ipRanges, allAllocatedIPv4)
if err != nil {
return fmt.Errorf("Failed to allocate uplink IPv4 address: %w", err)
}
n.config[ovnVolatileUplinkIPv4] = routerExtPortIPv4.String()
}
if uplinkIPv6Net != nil && routerExtPortIPv6 == nil {
// If IPv6 OVN ranges are specified by the uplink, allocate from them.
if uplinkNetConf["ipv6.ovn.ranges"] != "" {
dhcpSubnet := uplinkNet.DHCPv6Subnet()
allowedNets := []*net.IPNet{}
if dhcpSubnet != nil {
allowedNets = append(allowedNets, dhcpSubnet)
} else {
allowedNets = append(allowedNets, uplinkIPv6Net)
}
ipRanges, err := parseIPRanges(uplinkNetConf["ipv6.ovn.ranges"], allowedNets...)
if err != nil {
return fmt.Errorf("Failed to parse uplink IPv6 OVN ranges: %w", err)
}
routerExtPortIPv6, err = n.uplinkAllocateIP(ipRanges, allAllocatedIPv6)
if err != nil {
return fmt.Errorf("Failed to allocate uplink IPv6 address: %w", err)
}
} else {
// Otherwise use EUI64 derived from MAC address.
routerExtPortIPv6, err = eui64.ParseMAC(uplinkIPv6Net.IP, routerMAC)
if err != nil {
return err
}
}
n.config[ovnVolatileUplinkIPv6] = routerExtPortIPv6.String()
}
err = tx.UpdateNetwork(ctx, n.project, n.name, n.description, n.config)
if err != nil {
return fmt.Errorf("Failed saving allocated uplink network IPs: %w", err)
}
return nil
})
if err != nil {
return nil, err
}
}
// Configure variables needed to configure OVN router.
if uplinkIPv4Net != nil && routerExtPortIPv4 != nil {
routerExtPortIPv4Net := &net.IPNet{
Mask: uplinkIPv4Net.Mask,
IP: routerExtPortIPv4,
}
v.routerExtPortIPv4Net = routerExtPortIPv4Net.String()
}
if uplinkIPv6Net != nil {
routerExtPortIPv6Net := &net.IPNet{
Mask: uplinkIPv6Net.Mask,
IP: routerExtPortIPv6,
}
v.routerExtPortIPv6Net = routerExtPortIPv6Net.String()
}
return v, nil
}
// uplinkAllAllocatedIPs gets a list of all IPv4 and IPv6 addresses allocated to OVN networks connected to uplink.
func (n *ovn) uplinkAllAllocatedIPs(ctx context.Context, tx *db.ClusterTx, uplinkNetName string) ([]net.IP, []net.IP, error) {
// Get all managed networks across all projects.
projectNetworks, err := tx.GetCreatedNetworks(ctx)
if err != nil {
return nil, nil, fmt.Errorf("Failed to load all networks: %w", err)
}
v4IPs := make([]net.IP, 0)
v6IPs := make([]net.IP, 0)
for _, networks := range projectNetworks {
for _, netInfo := range networks {
if netInfo.Type != "ovn" || netInfo.Config["network"] != uplinkNetName {
continue
}
for _, k := range []string{ovnVolatileUplinkIPv4, ovnVolatileUplinkIPv6} {
if netInfo.Config[k] != "" {
ip := net.ParseIP(netInfo.Config[k])
if ip != nil {
if ip.To4() != nil {
v4IPs = append(v4IPs, ip)
} else {
v6IPs = append(v6IPs, ip)
}
}
}
}
}
}
return v4IPs, v6IPs, nil
}
// uplinkAllocateIP allocates a free IP from one of the IP ranges.
func (n *ovn) uplinkAllocateIP(ipRanges []*iprange.Range, allAllocated []net.IP) (net.IP, error) {
for _, ipRange := range ipRanges {
inc := big.NewInt(1)
// Convert IPs in range to native representations to allow incrementing and comparison.
startIP := ipRange.Start.To4()
if startIP == nil {
startIP = ipRange.Start.To16()
}
endIP := ipRange.End.To4()
if endIP == nil {
endIP = ipRange.End.To16()
}
startBig := big.NewInt(0)
startBig.SetBytes(startIP)
endBig := big.NewInt(0)
endBig.SetBytes(endIP)
// Iterate through IPs in range, return the first unallocated one found.
for {
if startBig.Cmp(endBig) > 0 {
break
}
ip := net.IP(startBig.Bytes())
// Check IP is not already allocated.
freeIP := true
if slices.ContainsFunc(allAllocated, ip.Equal) {
freeIP = false
}
if !freeIP {
startBig.Add(startBig, inc)
continue
}
return ip, nil
}
}
return nil, errors.New("No free IPs available")
}
// startUplinkPort performs any network start up logic needed to connect the uplink connection to OVN.
func (n *ovn) startUplinkPort() error {
if n.config["network"] == "none" {
return nil
}
// Uplink network must be in default project.
uplinkNet, err := LoadByName(n.state, api.ProjectDefaultName, n.config["network"])
if err != nil {
return fmt.Errorf("Failed loading uplink network %q: %w", n.config["network"], err)
}
// Lock uplink network so that if multiple OVN networks are trying to connect to the same uplink we don't
// race each other setting up the connection.
unlock, err := locking.Lock(context.TODO(), n.uplinkOperationLockName(uplinkNet))
if err != nil {
return err
}
defer unlock()
switch uplinkNet.Type() {
case "bridge":
return n.startUplinkPortBridge(uplinkNet)
case "physical":
return n.startUplinkPortPhysical(uplinkNet)
}
return fmt.Errorf("Failed starting uplink port, network type %q unsupported as OVN uplink", uplinkNet.Type())
}
// uplinkOperationLockName returns the lock name to use for operations on the uplink network.
func (n *ovn) uplinkOperationLockName(uplinkNet Network) string {
return fmt.Sprintf("network.ovn.%s", uplinkNet.Name())
}
// uplinkPortBridgeVars returns the uplink port bridge variables needed for port start/stop.
func (n *ovn) uplinkPortBridgeVars(uplinkNet Network) *ovnUplinkPortBridgeVars {
ovsBridge := fmt.Sprintf("incusovn%d", uplinkNet.ID())
return &ovnUplinkPortBridgeVars{
ovsBridge: ovsBridge,
uplinkEnd: fmt.Sprintf("%sa", ovsBridge),
ovsEnd: fmt.Sprintf("%sb", ovsBridge),
}
}
// startUplinkPortBridge creates veth pair (if doesn't exist), creates OVS bridge (if doesn't exist) and
// connects veth pair to uplink bridge and OVS bridge.
func (n *ovn) startUplinkPortBridge(uplinkNet Network) error {
if uplinkNet.Config()["bridge.driver"] != "openvswitch" {
return n.startUplinkPortBridgeNative(uplinkNet, uplinkNet.Name())
}
return n.startUplinkPortBridgeOVS(uplinkNet, uplinkNet.Name())
}
// startUplinkPortBridgeNative connects an OVN logical router to an uplink native bridge.
func (n *ovn) startUplinkPortBridgeNative(uplinkNet Network, bridgeDevice string) error {
// Do this after gaining lock so that on failure we revert before release locking.
reverter := revert.New()
defer reverter.Fail()
// If uplink is a native bridge, then use a separate OVS bridge with veth pair connection to native bridge.
vars := n.uplinkPortBridgeVars(uplinkNet)
// Create veth pair if needed.
if !InterfaceExists(vars.uplinkEnd) && !InterfaceExists(vars.ovsEnd) {
veth := &ip.Veth{
Link: ip.Link{
Name: vars.uplinkEnd,
},
Peer: ip.Link{
Name: vars.ovsEnd,
},
}
err := veth.Add()
if err != nil {
return fmt.Errorf("Failed to create the uplink veth interfaces %q and %q: %w", vars.uplinkEnd, vars.ovsEnd, err)
}
reverter.Add(func() { _ = veth.Delete() })
}
// Ensure that the veth interfaces inherit the uplink bridge's MTU (which the OVS bridge also inherits).
uplinkNetConfig := uplinkNet.Config()
// Uplink may have type "bridge" or "physical"
uplinkNetMTU, hasBridgeMTU := uplinkNetConfig["bridge.mtu"]
if !hasBridgeMTU {
uplinkNetMTU = uplinkNetConfig["mtu"]
}
if uplinkNetMTU != "" {
mtu, err := strconv.ParseUint(uplinkNetMTU, 10, 32)
if err != nil {
return fmt.Errorf("Invalid uplink MTU %q: %w", uplinkNetMTU, err)
}
uplinkEndLink := &ip.Link{Name: vars.uplinkEnd}
err = uplinkEndLink.SetMTU(uint32(mtu))
if err != nil {
return fmt.Errorf("Failed setting MTU %q on %q: %w", uplinkNetMTU, uplinkEndLink.Name, err)
}
ovsEndLink := &ip.Link{Name: vars.ovsEnd}
err = ovsEndLink.SetMTU(uint32(mtu))
if err != nil {
return fmt.Errorf("Failed setting MTU %q on %q: %w", uplinkNetMTU, ovsEndLink.Name, err)
}
}
// Ensure correct sysctls are set on uplink veth interfaces to avoid getting IPv6 link-local addresses.
if util.PathExists("/proc/sys/net/ipv6") {
err := localUtil.SysctlSet(
fmt.Sprintf("net/ipv6/conf/%s/disable_ipv6", vars.uplinkEnd), "1",
fmt.Sprintf("net/ipv6/conf/%s/disable_ipv6", vars.ovsEnd), "1",
fmt.Sprintf("net/ipv6/conf/%s/forwarding", vars.uplinkEnd), "0",
fmt.Sprintf("net/ipv6/conf/%s/forwarding", vars.ovsEnd), "0",
)
if err != nil {
return fmt.Errorf("Failed to configure uplink veth interfaces %q and %q: %w", vars.uplinkEnd, vars.ovsEnd, err)
}
}
// Connect uplink end of veth pair to uplink bridge and bring up.
link := &ip.Link{Name: vars.uplinkEnd}
err := link.SetMaster(bridgeDevice)
if err != nil {
return fmt.Errorf("Failed to connect uplink veth interface %q to uplink bridge %q: %w", vars.uplinkEnd, bridgeDevice, err)
}
link = &ip.Link{Name: vars.uplinkEnd}
err = link.SetUp()
if err != nil {
return fmt.Errorf("Failed to bring up uplink veth interface %q: %w", vars.uplinkEnd, err)
}
// Ensure uplink OVS end veth interface is up.
link = &ip.Link{Name: vars.ovsEnd}
err = link.SetUp()
if err != nil {
return fmt.Errorf("Failed to bring up uplink veth interface %q: %w", vars.ovsEnd, err)
}
// Create uplink OVS bridge if needed.
vswitch, err := n.state.OVS()
if err != nil {
return fmt.Errorf("Failed to connect to OVS: %w", err)
}
err = vswitch.CreateBridge(context.TODO(), vars.ovsBridge, true, nil, 0)
if err != nil {
return fmt.Errorf("Failed to create uplink OVS bridge %q: %w", vars.ovsBridge, err)
}
// Connect OVS end veth interface to OVS bridge.
err = vswitch.CreateBridgePort(context.TODO(), vars.ovsBridge, vars.ovsEnd, true)
if err != nil {
return fmt.Errorf("Failed to connect uplink veth interface %q to uplink OVS bridge %q: %w", vars.ovsEnd, vars.ovsBridge, err)
}
// Associate OVS bridge to logical OVN provider.
err = vswitch.AddOVNBridgeMapping(context.TODO(), vars.ovsBridge, uplinkNet.Name())
if err != nil {
return fmt.Errorf("Failed to associate uplink OVS bridge %q to OVN provider %q: %w", vars.ovsBridge, uplinkNet.Name(), err)
}
// Attempt to learn uplink MAC.
n.pingOVNRouter()
reverter.Success()
return nil
}
// startUplinkPortBridgeOVS connects an OVN logical router to an uplink OVS bridge.
func (n *ovn) startUplinkPortBridgeOVS(uplinkNet Network, bridgeDevice string) error {
// Do this after gaining lock so that on failure we revert before release locking.
reverter := revert.New()
defer reverter.Fail()
// If uplink is an openvswitch bridge, have OVN logical provider connect directly to it.
vswitch, err := n.state.OVS()
if err != nil {
return fmt.Errorf("Failed to connect to OVS: %w", err)
}
err = vswitch.AddOVNBridgeMapping(context.TODO(), bridgeDevice, uplinkNet.Name())
if err != nil {
return fmt.Errorf("Failed to associate uplink OVS bridge %q to OVN provider %q: %w", bridgeDevice, uplinkNet.Name(), err)
}
// Attempt to learn uplink MAC.
n.pingOVNRouter()
reverter.Success()
return nil
}
// pingOVNRouter pings the OVN router's external IP addresses to attempt to trigger MAC learning on uplink.
// This is to work around a bug in some versions of OVN.
func (n *ovn) pingOVNRouter() {
var ips []net.IP
for _, key := range []string{ovnVolatileUplinkIPv4, ovnVolatileUplinkIPv6} {
ip := net.ParseIP(n.config[key])
if ip != nil {
ips = append(ips, ip)
}
}
for i := range ips {
ip := ips[i] // Local var
// Now that the OVN router is connected to the uplink bridge, attempt to ping the OVN
// router's external IPv6 from the host running the uplink bridge in an attempt to trigger the
// OVN router to learn the uplink gateway's MAC address. This is to work around a bug in
// older versions of OVN that meant that the OVN router would not attempt to learn the external
// uplink IPv6 gateway MAC address when using SNAT, meaning that external IPv6 connectivity
// wouldn't work until the next router advertisement was sent (which could be several minutes).
// By pinging the OVN router's external IP this will trigger an NDP request from the uplink bridge
// which will cause the OVN router to learn its MAC address.
go func() {
var err error
// Try several attempts as it can take a few seconds for the network to come up.
for range 5 {
err = pingIP(context.TODO(), ip)
if err == nil {
n.logger.Debug("OVN router external IP address reachable", logger.Ctx{"ip": ip.String()})
return
}
time.Sleep(time.Second)
}
// We would expect this on a chassis node that isn't the active router gateway, it doesn't
// always indicate a problem.
n.logger.Debug("OVN router external IP address unreachable", logger.Ctx{"ip": ip.String(), "err": err})
}()
}
}
// startUplinkPortPhysical creates OVS bridge (if doesn't exist) and connects uplink interface to the OVS bridge.
func (n *ovn) startUplinkPortPhysical(uplinkNet Network) error {
// Do this after gaining lock so that on failure we revert before release locking.
reverter := revert.New()
defer reverter.Fail()
uplinkConfig := uplinkNet.Config()
uplinkHostName := GetHostDevice(uplinkConfig["parent"], uplinkConfig["vlan"])
if !InterfaceExists(uplinkHostName) {
return fmt.Errorf("Uplink network %q is not started (interface %q is missing)", uplinkNet.Name(), uplinkHostName)
}
// Detect if uplink interface is a native bridge.
if IsNativeBridge(uplinkHostName) {
return n.startUplinkPortBridgeNative(uplinkNet, uplinkHostName)
}
// Detect if uplink interface is a OVS bridge.
vswitch, err := n.state.OVS()
if err != nil {
return fmt.Errorf("Failed to connect to OVS: %w", err)
}
_, err = vswitch.GetBridge(context.TODO(), uplinkHostName)
if err != nil && !errors.Is(err, ovs.ErrNotFound) {
return err
} else if err == nil {
return n.startUplinkPortBridgeOVS(uplinkNet, uplinkHostName)
}
// If uplink is a normal physical interface, then use a separate OVS bridge and connect uplink to it.
vars := n.uplinkPortBridgeVars(uplinkNet)
// Check no global unicast IPs defined on uplink, as that may indicate it is in use by another application.
addresses, _, err := InterfaceStatus(uplinkHostName)
if err != nil {
return fmt.Errorf("Failed getting interface status for %q: %w", uplinkHostName, err)
}
if len(addresses) > 0 {
return fmt.Errorf("Cannot start network as uplink network interface %q has one or more IP addresses configured on it", uplinkHostName)
}
// Ensure correct sysctls are set on uplink interface to avoid getting IPv6 link-local addresses.
err = localUtil.SysctlSet(
fmt.Sprintf("net/ipv6/conf/%s/disable_ipv6", uplinkHostName), "1",
fmt.Sprintf("net/ipv6/conf/%s/forwarding", uplinkHostName), "0",
)
if err != nil {
return fmt.Errorf("Failed to configure uplink interface %q: %w", uplinkHostName, err)
}
// Create uplink OVS bridge if needed.
err = vswitch.CreateBridge(context.TODO(), vars.ovsBridge, true, nil, 0)
if err != nil {
return fmt.Errorf("Failed to create uplink OVS bridge %q: %w", vars.ovsBridge, err)
}
// Connect OVS end veth interface to OVS bridge.
err = vswitch.CreateBridgePort(context.TODO(), vars.ovsBridge, uplinkHostName, true)
if err != nil {
return fmt.Errorf("Failed to connect uplink interface %q to uplink OVS bridge %q: %w", uplinkHostName, vars.ovsBridge, err)
}
// Associate OVS bridge to logical OVN provider.
err = vswitch.AddOVNBridgeMapping(context.TODO(), vars.ovsBridge, uplinkNet.Name())
if err != nil {
return fmt.Errorf("Failed to associate uplink OVS bridge %q to OVN provider %q: %w", vars.ovsBridge, uplinkNet.Name(), err)
}
// Bring uplink interface up.
link := &ip.Link{Name: uplinkHostName}
err = link.SetUp()
if err != nil {
return fmt.Errorf("Failed to bring up uplink interface %q: %w", uplinkHostName, err)
}
// Attempt to learn uplink MAC.
n.pingOVNRouter()
reverter.Success()
return nil
}
// checkUplinkUse checks if uplink network is used by another OVN network.
func (n *ovn) checkUplinkUse() (bool, error) {
if n.config["network"] == "none" {
return false, nil
}
// Get all managed networks across all projects.
var err error
var projectNetworks map[string]map[int64]api.Network
err = n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
projectNetworks, err = tx.GetCreatedNetworks(ctx)
return err
})
if err != nil {
return false, fmt.Errorf("Failed to load all networks: %w", err)
}
for projectName, networks := range projectNetworks {
for _, network := range networks {
if (projectName == n.project && network.Name == n.name) || network.Type != "ovn" {
continue // Ignore our own DB record or non OVN networks.
}
// Check if another network is using our uplink.
if network.Config["network"] == n.config["network"] {
return true, nil
}
}
}
return false, nil
}
// deleteUplinkPort deletes the uplink connection.
func (n *ovn) deleteUplinkPort() error {
if n.config["network"] == "none" {
return nil
}
// Uplink network must be in default project.
if n.config["network"] != "" {
uplinkNet, err := LoadByName(n.state, api.ProjectDefaultName, n.config["network"])
if err != nil {
return fmt.Errorf("Failed loading uplink network %q: %w", n.config["network"], err)
}
// Lock uplink network so we don't race each other networks using the OVS uplink bridge.
unlock, err := locking.Lock(context.TODO(), n.uplinkOperationLockName(uplinkNet))
if err != nil {
return err
}
defer unlock()
switch uplinkNet.Type() {
case "bridge":
return n.deleteUplinkPortBridge(uplinkNet)
case "physical":
return n.deleteUplinkPortPhysical(uplinkNet)
}
return fmt.Errorf("Failed deleting uplink port, network type %q unsupported as OVN uplink", uplinkNet.Type())
}
return nil
}
// deleteUplinkPortBridge disconnects the uplink port from the bridge and performs any cleanup.
func (n *ovn) deleteUplinkPortBridge(uplinkNet Network) error {
if uplinkNet.Config()["bridge.driver"] != "openvswitch" {
return n.deleteUplinkPortBridgeNative(uplinkNet)
}
return n.deleteUplinkPortBridgeOVS(uplinkNet, uplinkNet.Name())
}
// deleteUplinkPortBridge deletes uplink OVS bridge, OVN bridge mappings and veth interfaces if not in use.
func (n *ovn) deleteUplinkPortBridgeNative(uplinkNet Network) error {
// Check OVS uplink bridge exists, if it does, check whether the uplink network is in use.
removeVeths := false
vars := n.uplinkPortBridgeVars(uplinkNet)
if InterfaceExists(vars.ovsBridge) {
uplinkUsed, err := n.checkUplinkUse()
if err != nil {
return err
}
// Remove OVS bridge if the uplink network isn't used by any other OVN networks.
if !uplinkUsed {
removeVeths = true
vswitch, err := n.state.OVS()
if err != nil {
return fmt.Errorf("Failed to connect to OVS: %w", err)
}
err = vswitch.RemoveOVNBridgeMapping(context.TODO(), vars.ovsBridge, uplinkNet.Name())
if err != nil {
return err
}
err = vswitch.DeleteBridge(context.TODO(), vars.ovsBridge)
if err != nil {
return err
}
}
} else {
removeVeths = true // Remove the veths if OVS bridge already gone.
}
// Remove the veth interfaces if they exist.
if removeVeths {
if InterfaceExists(vars.uplinkEnd) {
link := &ip.Link{Name: vars.uplinkEnd}
err := link.Delete()
if err != nil {
return fmt.Errorf("Failed to delete the uplink veth interface %q: %w", vars.uplinkEnd, err)
}
}
if InterfaceExists(vars.ovsEnd) {
link := &ip.Link{Name: vars.ovsEnd}
err := link.Delete()
if err != nil {
return fmt.Errorf("Failed to delete the uplink veth interface %q: %w", vars.ovsEnd, err)
}
}
}
return nil
}
// deleteUplinkPortBridge deletes OVN bridge mappings if not in use.
func (n *ovn) deleteUplinkPortBridgeOVS(uplinkNet Network, ovsBridge string) error {
uplinkUsed, err := n.checkUplinkUse()
if err != nil {
return err
}
// Remove uplink OVS bridge mapping if not in use by other OVN networks.
if !uplinkUsed {
vswitch, err := n.state.OVS()
if err != nil {
return fmt.Errorf("Failed to connect to OVS: %w", err)
}
err = vswitch.RemoveOVNBridgeMapping(context.TODO(), ovsBridge, uplinkNet.Name())
if err != nil {
return err
}
}
return nil
}
// deleteUplinkPortPhysical deletes uplink OVS bridge and OVN bridge mappings if not in use.
func (n *ovn) deleteUplinkPortPhysical(uplinkNet Network) error {
uplinkConfig := uplinkNet.Config()
uplinkHostName := GetHostDevice(uplinkConfig["parent"], uplinkConfig["vlan"])
// Detect if uplink interface is a native bridge.
if IsNativeBridge(uplinkHostName) {
return n.deleteUplinkPortBridgeNative(uplinkNet)
}
// Detect if uplink interface is a OVS bridge.
vswitch, err := n.state.OVS()
if err != nil {
return fmt.Errorf("Failed to connect to OVS: %w", err)
}
_, err = vswitch.GetBridge(context.TODO(), uplinkHostName)
if err != nil && !errors.Is(err, ovs.ErrNotFound) {
return err
} else if err == nil {
return n.deleteUplinkPortBridgeOVS(uplinkNet, uplinkHostName)
}
// Otherwise if uplink is normal physical interface, attempt cleanup of OVS bridge.
// Check OVS uplink bridge exists, if it does, check whether the uplink network is in use.
releaseIF := false
vars := n.uplinkPortBridgeVars(uplinkNet)
if InterfaceExists(vars.ovsBridge) {
uplinkUsed, err := n.checkUplinkUse()
if err != nil {
return err
}
// Remove OVS bridge if the uplink network isn't used by any other OVN networks.
if !uplinkUsed {
releaseIF = true
err = vswitch.RemoveOVNBridgeMapping(context.TODO(), vars.ovsBridge, uplinkNet.Name())
if err != nil {
return err
}
err = vswitch.DeleteBridge(context.TODO(), vars.ovsBridge)
if err != nil {
return err
}
}
} else {
releaseIF = true // Bring uplink interface down if not needed.
}
// Bring down uplink interface if not used and exists.
if releaseIF && InterfaceExists(uplinkHostName) {
link := &ip.Link{Name: uplinkHostName}
err := link.SetDown()
if err != nil {
return fmt.Errorf("Failed to bring down uplink interface %q: %w", uplinkHostName, err)
}
}
return nil
}
// FillConfig fills requested config with any default values.
func (n *ovn) FillConfig(config map[string]string) error {
if config["ipv4.address"] == "" {
config["ipv4.address"] = "auto"
}
if config["ipv6.address"] == "" {
content, err := os.ReadFile("/proc/sys/net/ipv6/conf/default/disable_ipv6")
if err == nil && string(content) == "0\n" {
config["ipv6.address"] = "auto"
}
}
// Now replace any "auto" keys with generated values.
err := n.populateAutoConfig(config)
if err != nil {
return fmt.Errorf("Failed generating auto config: %w", err)
}
return nil
}
// populateAutoConfig replaces "auto" in config with generated values.
func (n *ovn) populateAutoConfig(config map[string]string) error {
changedConfig := false
if config["ipv4.address"] == "auto" {
subnet, err := randomSubnetV4()
if err != nil {
return err
}
config["ipv4.address"] = subnet
if config["ipv4.nat"] == "" {
config["ipv4.nat"] = "true"
}
changedConfig = true
}
if config["ipv6.address"] == "auto" {
subnet, err := randomSubnetV6()
if err != nil {
return err
}
config["ipv6.address"] = subnet
if config["ipv6.nat"] == "" {
config["ipv6.nat"] = "true"
}
changedConfig = true
}
// Re-validate config if changed.
if changedConfig && n.state != nil {
return n.Validate(config, request.ClientTypeNormal)
}
return nil
}
// Create sets up network in OVN Northbound database.
func (n *ovn) Create(clientType request.ClientType) error {
n.logger.Debug("Create", logger.Ctx{"clientType": clientType, "config": n.config})
// We only need to setup the OVN Northbound database once, not on every clustered node.
if clientType == request.ClientTypeNormal {
err := n.setup(false)
if err != nil {
return err
}
}
return nil
}
// allowedUplinkNetworks returns a list of allowed networks to use as uplinks based on project restrictions.
func (n *ovn) allowedUplinkNetworks(p *api.Project) ([]string, error) {
var uplinkNetworkNames []string
err := n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
// Uplink networks are always from the default project.
networks, err := tx.GetCreatedNetworksByProject(ctx, api.ProjectDefaultName)
if err != nil {
return fmt.Errorf("Failed getting uplink networks: %w", err)
}
// Add any compatible networks to the uplink network list.
for _, network := range networks {
if network.Type == "bridge" || network.Type == "physical" {
uplinkNetworkNames = append(uplinkNetworkNames, network.Name)
}
}
return nil
})
if err != nil {
return nil, err
}
// If project is not restricted, return full network list.
if util.IsFalseOrEmpty(p.Config["restricted"]) {
return uplinkNetworkNames, nil
}
allowedUplinkNetworkNames := []string{}
// There are no allowed networks if restricted.networks.uplinks is not set.
if p.Config["restricted.networks.uplinks"] == "" {
return allowedUplinkNetworkNames, nil
}
// Parse the allowed uplinks and return any that are present in the actual defined networks.
allowedRestrictedUplinks := util.SplitNTrimSpace(p.Config["restricted.networks.uplinks"], ",", -1, false)
for _, allowedRestrictedUplink := range allowedRestrictedUplinks {
if slices.Contains(uplinkNetworkNames, allowedRestrictedUplink) {
allowedUplinkNetworkNames = append(allowedUplinkNetworkNames, allowedRestrictedUplink)
}
}
return allowedUplinkNetworkNames, nil
}
// validateUplinkNetwork checks if uplink network is allowed, and if empty string is supplied then tries to select
// an uplink network from the allowedUplinkNetworks() list if there is only one allowed network.
// Returns chosen uplink network name to use.
func (n *ovn) validateUplinkNetwork(p *api.Project, uplinkNetworkName string) (string, error) {
allowedUplinkNetworks, err := n.allowedUplinkNetworks(p)
if err != nil {
return "", err
}
if uplinkNetworkName != "" {
if !slices.Contains(allowedUplinkNetworks, uplinkNetworkName) {
return "", fmt.Errorf(`Option "network" value %q is not one of the allowed uplink networks in project`, uplinkNetworkName)
}
return uplinkNetworkName, nil
}
allowedNetworkCount := len(allowedUplinkNetworks)
if allowedNetworkCount == 0 {
return "", errors.New(`No allowed uplink networks in project`)
} else if allowedNetworkCount == 1 {
// If there is only one allowed uplink network then use it if not specified by user.
return allowedUplinkNetworks[0], nil
}
return "", errors.New(`Option "network" is required`)
}
// getDHCPv4Reservations returns list DHCP IPv4 reservations from NICs connected to this network.
func (n *ovn) getDHCPv4Reservations() ([]iprange.Range, error) {
routerIntPortIPv4, ipv4Net, err := n.parseRouterIntPortIPv4Net()
if err != nil {
return nil, fmt.Errorf("Failed parsing router's internal port IPv4 Net for DHCP reservation: %w", err)
}
var dhcpReserveIPv4s []iprange.Range
if routerIntPortIPv4 != nil {
if n.config["ipv4.dhcp.ranges"] == "" {
dhcpReserveIPv4s = []iprange.Range{{Start: routerIntPortIPv4}, {Start: dhcpalloc.GetIP(ipv4Net, -2)}}
} else {
allowedNets := []*net.IPNet{n.DHCPv4Subnet()}
dhcpRanges, err := parseIPRanges(n.config["ipv4.dhcp.ranges"], allowedNets...)
if err != nil {
return nil, err
}
sort.Slice(dhcpRanges, func(i, j int) bool {
return bytes.Compare(dhcpRanges[i].Start, dhcpRanges[j].Start) < 0
})
reserverdIPs, err := complementRanges(dhcpRanges, ipv4Net)
if err != nil {
return nil, err
}
dhcpReserveIPv4s = append(dhcpReserveIPv4s, reserverdIPs...)
if !ipInRanges(routerIntPortIPv4, dhcpReserveIPv4s) {
dhcpReserveIPv4s = append(dhcpReserveIPv4s, iprange.Range{Start: routerIntPortIPv4})
}
// Convert the 4-byte IPv4 address returned by 'dhcpalloc.GetIP' to a 16-byte form
// using net.ParseIP, to ensure compatibility with other IPs stored in 16-byte format.
// This is necessary because direct comparison with 4-byte IPs would fail.
ovnRouter := net.ParseIP(dhcpalloc.GetIP(ipv4Net, -2).String())
if !ipInRanges(ovnRouter, dhcpReserveIPv4s) {
dhcpReserveIPv4s = append(dhcpReserveIPv4s, iprange.Range{Start: ovnRouter})
}
}
}
err = UsedByInstanceDevices(n.state, n.Project(), n.Name(), n.Type(), func(inst db.InstanceArgs, nicName string, nicConfig map[string]string) error {
ip := net.ParseIP(nicConfig["ipv4.address"])
if ip != nil {
if !ipInRanges(ip, dhcpReserveIPv4s) {
dhcpReserveIPv4s = append(dhcpReserveIPv4s, iprange.Range{Start: ip})
}
}
return nil
})
if err != nil {
return nil, err
}
return dhcpReserveIPv4s, nil
}
func (n *ovn) setup(update bool) error {
// If we are in mock mode, just no-op.
if n.state.OS.MockMode {
return nil
}
n.logger.Debug("Setting up network")
reverter := revert.New()
defer reverter.Fail()
var routerExtPortIPv4, routerExtPortIPv6 net.IP
var routerExtPortIPv4Net, routerExtPortIPv6Net *net.IPNet
// Record updated config so we can store back into DB and n.config variable.
updatedConfig := make(map[string]string)
// Load the project to get uplink network restrictions.
var p *api.Project
var projectID int64
err := n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
project, err := dbCluster.GetProject(ctx, tx.Tx(), n.project)
if err != nil {
return err
}
projectID = int64(project.ID)
p, err = project.ToAPI(ctx, tx.Tx())
return err
})
if err != nil {
return fmt.Errorf("Failed to load network restrictions from project %q: %w", n.project, err)
}
// Check project restrictions and get uplink network to use.
uplinkNetwork := "none"
if n.config["network"] != "none" {
uplinkNetwork, err = n.validateUplinkNetwork(p, n.config["network"])
if err != nil {
return err
}
}
// Ensure automatically selected uplink network is saved into "network" key.
if uplinkNetwork != n.config["network"] {
updatedConfig["network"] = uplinkNetwork
}
// Get bridge MTU to use.
bridgeMTU := n.getBridgeMTU()
if bridgeMTU == 0 {
// If no manual bridge MTU specified, derive it from the underlay network.
bridgeMTU, err = n.getOptimalBridgeMTU()
if err != nil {
return fmt.Errorf("Failed getting optimal bridge MTU: %w", err)
}
// Save to config so the value can be read by instances connecting to network.
updatedConfig["bridge.mtu"] = fmt.Sprintf("%d", bridgeMTU)
}
// Get a list of all NICs connected to this network that have static DHCP IPv4 reservations.
dhcpReserveIPv4s, err := n.getDHCPv4Reservations()
if err != nil {
return fmt.Errorf("Failed getting DHCPv4 IP reservations: %w", err)
}
// Apply any config dynamically generated to the current config and store back to DB in single transaction.
if len(updatedConfig) > 0 {
maps.Copy(n.config, updatedConfig)
err := n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
err = tx.UpdateNetwork(ctx, n.project, n.name, n.description, n.config)
if err != nil {
return fmt.Errorf("Failed saving updated network config: %w", err)
}
return nil
})
if err != nil {
return err
}
}
// Get router MAC address.
routerMAC, err := n.getRouterMAC()
if err != nil {
return err
}
// Setup uplink port (do this first to check uplink is suitable).
uplinkNet, err := n.setupUplinkPort(routerMAC)
if err != nil {
return err
}
// Parse router IP config.
if uplinkNet != nil && uplinkNet.routerExtPortIPv4Net != "" {
routerExtPortIPv4, routerExtPortIPv4Net, err = net.ParseCIDR(uplinkNet.routerExtPortIPv4Net)
if err != nil {
return fmt.Errorf("Failed parsing router's external uplink port IPv4 Net: %w", err)
}
}
if uplinkNet != nil && uplinkNet.routerExtPortIPv6Net != "" {
routerExtPortIPv6, routerExtPortIPv6Net, err = net.ParseCIDR(uplinkNet.routerExtPortIPv6Net)
if err != nil {
return fmt.Errorf("Failed parsing router's external uplink port IPv6 Net: %w", err)
}
}
routerIntPortIPv4, routerIntPortIPv4Net, err := n.parseRouterIntPortIPv4Net()
if err != nil {
return fmt.Errorf("Failed parsing router's internal port IPv4 Net: %w", err)
}
routerIntPortIPv6, routerIntPortIPv6Net, err := n.parseRouterIntPortIPv6Net()
if err != nil {
return fmt.Errorf("Failed parsing router's internal port IPv6 Net: %w", err)
}
if n.config["network"] != "none" && routerIntPortIPv4 == nil && routerIntPortIPv6 == nil {
return errors.New("IPv4 or IPv6 subnets must be specified on a non-isolated OVN network")
}
// Create chassis group.
err = n.ovnnb.CreateChassisGroup(context.TODO(), n.getChassisGroupName(), update)
if err != nil {
return err
}
if !update {
reverter.Add(func() { _ = n.ovnnb.DeleteChassisGroup(context.TODO(), n.getChassisGroupName()) })
}
// Configure logical router.
if routerIntPortIPv4 != nil || routerIntPortIPv6 != nil {
// Create logical router.
err = n.ovnnb.CreateLogicalRouter(context.TODO(), n.getRouterName(), update)
if err != nil {
return fmt.Errorf("Failed adding router: %w", err)
}
if !update {
reverter.Add(func() { _ = n.ovnnb.DeleteLogicalRouter(context.TODO(), n.getRouterName()) })
}
} else {
err := n.ovnnb.DeleteLogicalRouter(context.TODO(), n.getRouterName())
if err != nil && !errors.Is(err, networkOVN.ErrNotFound) {
return fmt.Errorf("Failed deleting router: %w", err)
}
}
// Generate external router port IPs (in CIDR format).
extRouterIPs := []*net.IPNet{}
if routerExtPortIPv4Net != nil {
extRouterIPs = append(extRouterIPs, &net.IPNet{
IP: routerExtPortIPv4,
Mask: routerExtPortIPv4Net.Mask,
})
}
if routerExtPortIPv6Net != nil {
extRouterIPs = append(extRouterIPs, &net.IPNet{
IP: routerExtPortIPv6,
Mask: routerExtPortIPv6Net.Mask,
})
}
if len(extRouterIPs) > 0 {
err = n.ovnnb.CreateLogicalSwitch(context.TODO(), n.getExtSwitchName(), update)
if err != nil {
return fmt.Errorf("Failed adding external switch: %w", err)
}
if !update {
reverter.Add(func() { _ = n.ovnnb.DeleteLogicalSwitch(context.TODO(), n.getExtSwitchName()) })
}
// Create external router port.
err = n.ovnnb.CreateLogicalRouterPort(context.TODO(), n.getRouterName(), n.getRouterExtPortName(), routerMAC, bridgeMTU, extRouterIPs, n.getChassisGroupName(), update)
if err != nil {
return fmt.Errorf("Failed adding external router port: %w", err)
}
if !update {
reverter.Add(func() {
_ = n.ovnnb.DeleteLogicalRouterPort(context.TODO(), n.getRouterName(), n.getRouterExtPortName())
})
}
// Create external switch port and link to router port.
err = n.ovnnb.CreateLogicalSwitchPort(context.TODO(), n.getExtSwitchName(), n.getExtSwitchRouterPortName(), nil, update)
if err != nil {
return fmt.Errorf("Failed adding external switch router port: %w", err)
}
if !update {
reverter.Add(func() {
_ = n.ovnnb.DeleteLogicalSwitchPort(context.TODO(), n.getExtSwitchName(), n.getExtSwitchRouterPortName())
})
}
err = n.ovnnb.UpdateLogicalSwitchPortLinkRouter(context.TODO(), n.getExtSwitchRouterPortName(), n.getRouterExtPortName())
if err != nil {
return fmt.Errorf("Failed linking external router port to external switch port: %w", err)
}
// Create external switch port and link to external provider network.
err = n.ovnnb.CreateLogicalSwitchPort(context.TODO(), n.getExtSwitchName(), n.getExtSwitchProviderPortName(), nil, update)
if err != nil {
return fmt.Errorf("Failed adding external switch provider port: %w", err)
}
if !update {
reverter.Add(func() {
_ = n.ovnnb.DeleteLogicalSwitchPort(context.TODO(), n.getExtSwitchName(), n.getExtSwitchProviderPortName())
})
}
if uplinkNet != nil {
err = n.ovnnb.UpdateLogicalSwitchPortLinkProviderNetwork(context.TODO(), n.getExtSwitchProviderPortName(), uplinkNet.extSwitchProviderName)
if err != nil {
return fmt.Errorf("Failed linking external switch provider port to external provider network: %w", err)
}
}
// Remove any existing SNAT rules on update. As currently these are only defined from the network
// config rather than from any instance NIC config, so we can re-create the active config below.
if update {
err = n.ovnnb.DeleteLogicalRouterNAT(context.TODO(), n.getRouterName(), "snat", true)
if err != nil {
return fmt.Errorf("Failed removing existing router SNAT rules: %w", err)
}
}
// Add SNAT rules.
if util.IsTrue(n.config["ipv4.nat"]) && routerIntPortIPv4Net != nil && routerExtPortIPv4 != nil {
snatIP := routerExtPortIPv4
if n.config["ipv4.nat.address"] != "" {
snatIP = net.ParseIP(n.config["ipv4.nat.address"])
if snatIP == nil {
return fmt.Errorf("Failed parsing %q", "ipv4.nat.address")
}
}
err = n.ovnnb.CreateLogicalRouterNAT(context.TODO(), n.getRouterName(), "snat", routerIntPortIPv4Net, snatIP, nil, false, update)
if err != nil {
return fmt.Errorf("Failed adding router IPv4 SNAT rule: %w", err)
}
}
if util.IsTrue(n.config["ipv6.nat"]) && routerIntPortIPv6Net != nil && routerExtPortIPv6 != nil {
snatIP := routerExtPortIPv6
if n.config["ipv6.nat.address"] != "" {
snatIP = net.ParseIP(n.config["ipv6.nat.address"])
if snatIP == nil {
return fmt.Errorf("Failed parsing %q", "ipv6.nat.address")
}
}
err = n.ovnnb.CreateLogicalRouterNAT(context.TODO(), n.getRouterName(), "snat", routerIntPortIPv6Net, snatIP, nil, false, update)
if err != nil {
return fmt.Errorf("Failed adding router IPv6 SNAT rule: %w", err)
}
}
// Check if uplink network states its gateway mac for static MAC binding.
if uplinkNet != nil && n.config["network"] != "none" {
// Load the uplink network.
uplinkNetworkObj, err := LoadByName(n.state, api.ProjectDefaultName, n.config["network"])
if err != nil {
return fmt.Errorf("Failed loading uplink network %q: %w", n.config["network"], err)
}
uplinkConfig := uplinkNetworkObj.Config()
// Handle IPv4 MAC.
if uplinkConfig["ipv4.gateway.hwaddr"] != "" {
// Set a static MAc binding for the gateway's IP and MAC.
uplinkGatewayIP, _, err := net.ParseCIDR(uplinkConfig["ipv4.gateway"])
if err != nil {
return err
}
uplinkGatewayMAC, err := net.ParseMAC(uplinkConfig["ipv4.gateway.hwaddr"])
if err != nil {
return err
}
err = n.ovnnb.CreateStaticMACBinding(context.TODO(), n.getRouterExtPortName(), uplinkGatewayIP, uplinkGatewayMAC, true)
if err != nil {
return err
}
}
// Handle IPv6 MAC.
if uplinkConfig["ipv6.gateway.hwaddr"] != "" {
// Set a static MAc binding for the gateway's IP and MAC.
uplinkGatewayIP, _, err := net.ParseCIDR(uplinkConfig["ipv6.gateway"])
if err != nil {
return err
}
uplinkGatewayMAC, err := net.ParseMAC(uplinkConfig["ipv6.gateway.hwaddr"])
if err != nil {
return err
}
err = n.ovnnb.CreateStaticMACBinding(context.TODO(), n.getRouterExtPortName(), uplinkGatewayIP, uplinkGatewayMAC, true)
if err != nil {
return err
}
}
// Clear any leftover MAC binding.
err = n.ovnnb.DeleteStaticMACBindings(context.TODO(), n.getRouterExtPortName(), uplinkConfig["ipv4.gateway.hwaddr"] == "", uplinkConfig["ipv6.gateway.hwaddr"] == "")
if err != nil {
return err
}
}
// Clear default routes (if existing) and re-apply based on current config.
defaultIPv4Route := net.IPNet{IP: net.IPv4zero, Mask: net.CIDRMask(0, 32)}
defaultIPv6Route := net.IPNet{IP: net.IPv6zero, Mask: net.CIDRMask(0, 128)}
deleteRoutes := []net.IPNet{defaultIPv4Route, defaultIPv6Route}
defaultRoutes := make([]networkOVN.OVNRouterRoute, 0, 2)
if routerIntPortIPv4Net != nil {
// If l3only mode is enabled then each instance IPv4 will get its own /32 route added when
// the instance NIC starts. However to stop packets toward unknown IPs within the internal
// subnet escaping onto the uplink network we add a less specific discard route for the
// whole internal subnet.
if util.IsTrue(n.config["ipv4.l3only"]) {
defaultRoutes = append(defaultRoutes, networkOVN.OVNRouterRoute{
Prefix: *routerIntPortIPv4Net,
Discard: true,
})
} else {
deleteRoutes = append(deleteRoutes, *routerIntPortIPv4Net)
}
}
if routerIntPortIPv6Net != nil {
// If l3only mode is enabled then each instance IPv6 will get its own /128 route added when
// the instance NIC starts. However to stop packets toward unknown IPs within the internal
// subnet escaping onto the uplink network we add a less specific discard route for the
// whole internal subnet.
if util.IsTrue(n.config["ipv6.l3only"]) {
defaultRoutes = append(defaultRoutes, networkOVN.OVNRouterRoute{
Prefix: *routerIntPortIPv6Net,
Discard: true,
})
} else {
deleteRoutes = append(deleteRoutes, *routerIntPortIPv6Net)
}
}
if uplinkNet.routerExtGwIPv4 != nil {
defaultRoutes = append(defaultRoutes, networkOVN.OVNRouterRoute{
Prefix: defaultIPv4Route,
NextHop: uplinkNet.routerExtGwIPv4,
Port: n.getRouterExtPortName(),
})
}
if uplinkNet.routerExtGwIPv6 != nil {
defaultRoutes = append(defaultRoutes, networkOVN.OVNRouterRoute{
Prefix: defaultIPv6Route,
NextHop: uplinkNet.routerExtGwIPv6,
Port: n.getRouterExtPortName(),
})
}
if len(deleteRoutes) > 0 {
err = n.ovnnb.DeleteLogicalRouterRoute(context.TODO(), n.getRouterName(), deleteRoutes...)
if err != nil {
return fmt.Errorf("Failed removing default routes: %w", err)
}
}
if len(defaultRoutes) > 0 {
err = n.ovnnb.CreateLogicalRouterRoute(context.TODO(), n.getRouterName(), update, defaultRoutes...)
if err != nil {
return fmt.Errorf("Failed adding default routes: %w", err)
}
}
}
// Gather internal router port IPs (in CIDR format).
intRouterIPs := []*net.IPNet{}
intSubnets := []net.IPNet{}
if routerIntPortIPv4Net != nil {
intRouterIPNet := &net.IPNet{
IP: routerIntPortIPv4,
Mask: routerIntPortIPv4Net.Mask,
}
// In l3only mode the router's internal IP has a /32 mask instead of the internal subnet's mask.
if util.IsTrue(n.config["ipv4.l3only"]) {
intRouterIPNet.Mask = net.CIDRMask(32, 32)
}
intRouterIPs = append(intRouterIPs, intRouterIPNet)
intSubnets = append(intSubnets, *routerIntPortIPv4Net)
}
if routerIntPortIPv6Net != nil {
intRouterIPNet := &net.IPNet{
IP: routerIntPortIPv6,
Mask: routerIntPortIPv6Net.Mask,
}
// In l3only mode the router's internal IP has a /128 mask instead of the internal subnet's mask.
if util.IsTrue(n.config["ipv6.l3only"]) {
intRouterIPNet.Mask = net.CIDRMask(128, 128)
}
intRouterIPs = append(intRouterIPs, intRouterIPNet)
intSubnets = append(intSubnets, *routerIntPortIPv6Net)
}
// Create internal logical switch if not updating.
err = n.ovnnb.CreateLogicalSwitch(context.TODO(), n.getIntSwitchName(), update)
if err != nil {
return fmt.Errorf("Failed adding internal switch: %w", err)
}
if !update {
reverter.Add(func() { _ = n.ovnnb.DeleteLogicalSwitch(context.TODO(), n.getIntSwitchName()) })
}
// Add any listed existing external interface.
if n.config["bridge.external_interfaces"] != "" {
for _, entry := range strings.Split(n.config["bridge.external_interfaces"], ",") {
entry = strings.TrimSpace(entry)
// Test for extended configuration of external interface.
entryParts := strings.Split(entry, "/")
ifParent := ""
vlanID := 0
if len(entryParts) == 3 {
vlanID, err = strconv.Atoi(entryParts[2])
if err != nil || vlanID < 1 || vlanID > 4094 {
vlanID = 0
n.logger.Warn("Ignoring invalid VLAN ID", logger.Ctx{"interface": entry, "vlanID": entryParts[2]})
} else {
entry = strings.TrimSpace(entryParts[0])
ifParent = strings.TrimSpace(entryParts[1])
}
}
iface, err := net.InterfaceByName(entry)
if err != nil {
if vlanID == 0 {
n.logger.Warn("Skipping attaching missing external interface", logger.Ctx{"interface": entry})
continue
}
// If the interface doesn't exist and VLAN ID was provided, create the missing interface.
ok, err := VLANInterfaceCreate(ifParent, entry, strconv.Itoa(vlanID), false)
if ok {
iface, err = net.InterfaceByName(entry)
}
if !ok || err != nil {
return fmt.Errorf("Failed to create external interface %q", entry)
}
} else if vlanID > 0 {
// If the interface exists and VLAN ID was provided, ensure it has the same parent and VLAN ID and is not attached to a different network.
linkInfo, err := ip.LinkByName(entry)
if err != nil {
return fmt.Errorf("Failed to get link info for external interface %q", entry)
}
if linkInfo.Kind != "vlan" || linkInfo.Parent != ifParent || linkInfo.VlanID != vlanID || (linkInfo.Master != "" && linkInfo.Master != n.name) {
return fmt.Errorf("External interface %q already in use", entry)
}
}
unused := true
addrs, err := iface.Addrs()
if err == nil {
for _, addr := range addrs {
ipAddr, _, err := net.ParseCIDR(addr.String())
if ipAddr != nil && err == nil && ipAddr.IsGlobalUnicast() {
unused = false
break
}
}
}
if !unused {
return errors.New("Only unconfigured network interfaces can be bridged")
}
lspName := networkOVN.OVNSwitchPort(fmt.Sprintf("%s-external-n%d-%s", n.getNetworkPrefix(), n.state.DB.Cluster.GetNodeID(), entry))
err = n.ovnnb.CreateLogicalSwitchPort(context.TODO(), n.getIntSwitchName(), lspName, &networkOVN.OVNSwitchPortOpts{
IPV4: "none",
IPV6: "none",
Promiscuous: true,
}, false)
if err != nil {
return fmt.Errorf("Failed to create logical switch port for %s: %w", entry, err)
}
reverter.Add(func() {
_ = n.ovnnb.DeleteLogicalSwitchPort(context.TODO(), n.getIntSwitchName(), lspName)
})
// Attach host side veth interface to bridge.
integrationBridge := n.state.GlobalConfig.NetworkOVNIntegrationBridge()
vswitch, err := n.state.OVS()
if err != nil {
return fmt.Errorf("Failed to connect to OVS: %w", err)
}
err = vswitch.CreateBridgePort(context.TODO(), integrationBridge, entry, true)
if err != nil {
return err
}
reverter.Add(func() { _ = vswitch.DeleteBridgePort(context.TODO(), integrationBridge, entry) })
// Link OVS port to OVN logical port.
err = vswitch.AssociateInterfaceOVNSwitchPort(context.TODO(), entry, string(lspName))
if err != nil {
return err
}
// Make sure the port is up.
link := &ip.Link{Name: entry}
err = link.SetUp()
if err != nil {
return fmt.Errorf("Failed to bring up the host interface %s: %w", entry, err)
}
}
}
// Setup IP allocation config on logical switch.
err = n.ovnnb.UpdateLogicalSwitchIPAllocation(context.TODO(), n.getIntSwitchName(), &networkOVN.OVNIPAllocationOpts{
PrefixIPv4: routerIntPortIPv4Net,
PrefixIPv6: routerIntPortIPv6Net,
ExcludeIPv4: dhcpReserveIPv4s,
})
if err != nil {
return fmt.Errorf("Failed setting IP allocation settings on internal switch: %w", err)
}
// Create internal switch address sets and add subnets to address set.
if update {
err = n.ovnnb.UpdateAddressSetAdd(context.TODO(), acl.OVNIntSwitchPortGroupAddressSetPrefix(n.ID()), intSubnets...)
if err != nil {
return fmt.Errorf("Failed adding internal subnet address set entries: %w", err)
}
} else {
err = n.ovnnb.CreateAddressSet(context.TODO(), acl.OVNIntSwitchPortGroupAddressSetPrefix(n.ID()), intSubnets...)
if err != nil {
return fmt.Errorf("Failed creating internal subnet address set entries: %w", err)
}
reverter.Add(func() {
_ = n.ovnnb.DeleteAddressSet(context.TODO(), acl.OVNIntSwitchPortGroupAddressSetPrefix(n.ID()))
})
}
if routerIntPortIPv4 != nil || routerIntPortIPv6 != nil {
// Apply router security policy.
err = n.logicalRouterPolicySetup(n.ovnnb)
if err != nil {
return fmt.Errorf("Failed applying router security policy: %w", err)
}
// Create internal router port.
err = n.ovnnb.CreateLogicalRouterPort(context.TODO(), n.getRouterName(), n.getRouterIntPortName(), routerMAC, bridgeMTU, intRouterIPs, "", update)
if err != nil {
return fmt.Errorf("Failed adding internal router port: %w", err)
}
if !update {
reverter.Add(func() {
_ = n.ovnnb.DeleteLogicalRouterPort(context.TODO(), n.getRouterName(), n.getRouterIntPortName())
})
}
} else {
err := n.ovnnb.DeleteLogicalRouterPort(context.TODO(), n.getRouterName(), n.getRouterIntPortName())
if err != nil && !errors.Is(err, ovs.ErrNotFound) {
return fmt.Errorf("Failed deleting logical router port: %w", err)
}
}
// Configure DHCP option sets.
var dhcpv4UUID, dhcpv6UUID networkOVN.OVNDHCPOptionsUUID
dhcpV4Subnet := n.DHCPv4Subnet()
dhcpV6Subnet := n.DHCPv6Subnet()
if update {
dhcpv4UUID, dhcpv6UUID, err = n.getDhcpOptionUUIDs()
if err != nil {
return err
}
var deleteDHCPRecords []networkOVN.OVNDHCPOptionsUUID
if dhcpV4Subnet == nil && dhcpv4UUID != "" {
deleteDHCPRecords = append(deleteDHCPRecords, dhcpv4UUID)
}
if dhcpV6Subnet == nil && dhcpv6UUID != "" {
deleteDHCPRecords = append(deleteDHCPRecords, dhcpv6UUID)
}
if len(deleteDHCPRecords) > 0 {
err = n.ovnnb.DeleteLogicalSwitchDHCPOption(context.TODO(), n.getIntSwitchName(), deleteDHCPRecords...)
if err != nil {
return fmt.Errorf("Failed deleting existing DHCP settings for internal switch: %w", err)
}
}
}
var dnsIPv4 []net.IP
var dnsIPv6 []net.IP
if n.config["dns.nameservers"] != "" {
for _, s := range util.SplitNTrimSpace(n.config["dns.nameservers"], ",", -1, false) {
nsIP := net.ParseIP(s)
if nsIP.To4() != nil {
dnsIPv4 = append(dnsIPv4, nsIP)
} else {
dnsIPv6 = append(dnsIPv6, nsIP)
}
}
} else {
if uplinkNet != nil {
dnsIPv4 = uplinkNet.dnsIPv4
dnsIPv6 = uplinkNet.dnsIPv6
}
if len(dnsIPv4) == 0 {
dnsIPv4 = []net.IP{routerIntPortIPv4}
}
if len(dnsIPv6) == 0 {
dnsIPv6 = []net.IP{routerIntPortIPv6}
}
}
var dhcpv4Created, dhcpv6Created bool
// Create DHCPv4 options for internal switch.
if dhcpV4Subnet != nil {
// In l3only mode we configure the DHCPv4 server to request the instances use a /32 subnet mask.
var dhcpV4Netmask string
if util.IsTrue(n.config["ipv4.l3only"]) {
dhcpV4Netmask = "255.255.255.255"
}
leaseTime := time.Hour * 1
if n.config["ipv4.dhcp.expiry"] != "" {
duration, err := time.ParseDuration(n.config["ipv4.dhcp.expiry"])
if err != nil {
return fmt.Errorf("Failed to parse expiry: %w", err)
}
leaseTime = duration
}
opts := &networkOVN.OVNDHCPv4Opts{
ServerID: routerIntPortIPv4,
ServerMAC: routerMAC,
Router: routerIntPortIPv4,
DomainName: n.getDomainName(),
LeaseTime: leaseTime,
MTU: bridgeMTU,
Netmask: dhcpV4Netmask,
DNSSearchList: n.getDNSSearchList(),
StaticRoutes: n.config["ipv4.dhcp.routes"],
RecursiveDNSServer: dnsIPv4,
}
err = n.ovnnb.UpdateLogicalSwitchDHCPv4Options(context.TODO(), n.getIntSwitchName(), dhcpv4UUID, dhcpV4Subnet, opts)
if err != nil {
return fmt.Errorf("Failed adding DHCPv4 settings for internal switch: %w", err)
}
if dhcpv4UUID == "" {
dhcpv4Created = true
}
}
// Create DHCPv6 options for internal switch.
if dhcpV6Subnet != nil {
opts := &networkOVN.OVNDHCPv6Opts{
ServerID: routerMAC,
DNSSearchList: n.getDNSSearchList(),
RecursiveDNSServer: dnsIPv6,
DHCPv6Stateless: util.IsFalseOrEmpty(n.config["ipv6.dhcp.stateful"]),
}
err = n.ovnnb.UpdateLogicalSwitchDHCPv6Options(context.TODO(), n.getIntSwitchName(), dhcpv6UUID, dhcpV6Subnet, opts)
if err != nil {
return fmt.Errorf("Failed adding DHCPv6 settings for internal switch: %w", err)
}
if dhcpv6UUID == "" {
dhcpv6Created = true
}
}
if update && (dhcpv4Created || dhcpv6Created) {
dhcpv4UUID, dhcpv6UUID, err = n.getDhcpOptionUUIDs()
if err != nil {
return err
}
ports, err := n.ovnnb.GetLogicalSwitchPorts(context.TODO(), n.getIntSwitchName())
if err != nil {
return err
}
for portName := range ports {
err := n.ovnnb.UpdateLogicalSwitchPortDHCP(context.TODO(), portName, dhcpv4UUID, dhcpv6UUID)
if err != nil {
return err
}
}
}
// Set IPv6 router advertisement settings.
if routerIntPortIPv6Net != nil {
adressMode := networkOVN.OVNIPv6AddressModeSLAAC
if dhcpV6Subnet != nil {
adressMode = networkOVN.OVNIPv6AddressModeDHCPStateless
if util.IsTrue(n.config["ipv6.dhcp.stateful"]) {
adressMode = networkOVN.OVNIPv6AddressModeDHCPStateful
}
}
var recursiveDNSServer net.IP
if len(dnsIPv6) > 0 {
recursiveDNSServer = dnsIPv6[0] // OVN only supports 1 RA DNS server.
}
err = n.ovnnb.UpdateLogicalRouterPort(context.TODO(), n.getRouterIntPortName(), &networkOVN.OVNIPv6RAOpts{
AddressMode: adressMode,
SendPeriodic: true,
DNSSearchList: n.getDNSSearchList(),
RecursiveDNSServer: recursiveDNSServer,
MTU: bridgeMTU,
// Keep these low until we support DNS search domains via DHCPv4, as otherwise RA DNSSL
// won't take effect until advert after DHCPv4 has run on instance.
MinInterval: time.Duration(time.Second * 30),
MaxInterval: time.Duration(time.Minute * 1),
})
if err != nil {
return fmt.Errorf("Failed setting internal router port IPv6 advertisement settings: %w", err)
}
} else {
err = n.ovnnb.UpdateLogicalRouterPort(context.TODO(), n.getRouterIntPortName(), &networkOVN.OVNIPv6RAOpts{})
if err != nil && !errors.Is(err, networkOVN.ErrNotFound) {
return fmt.Errorf("Failed removing internal router port IPv6 advertisement settings: %w", err)
}
}
// Create internal switch port and link to router port.
if routerIntPortIPv4Net != nil || routerIntPortIPv6Net != nil {
err = n.ovnnb.CreateLogicalSwitchPort(context.TODO(), n.getIntSwitchName(), n.getIntSwitchRouterPortName(), nil, update)
if err != nil {
return fmt.Errorf("Failed adding internal switch router port: %w", err)
}
if !update {
reverter.Add(func() {
_ = n.ovnnb.DeleteLogicalSwitchPort(context.TODO(), n.getIntSwitchName(), n.getIntSwitchRouterPortName())
})
}
err = n.ovnnb.UpdateLogicalSwitchPortLinkRouter(context.TODO(), n.getIntSwitchRouterPortName(), n.getRouterIntPortName())
if err != nil {
return fmt.Errorf("Failed linking internal router port to internal switch port: %w", err)
}
} else {
err := n.ovnnb.DeleteLogicalSwitchPort(context.TODO(), n.getIntSwitchName(), n.getIntSwitchRouterPortName())
if err != nil && !errors.Is(err, networkOVN.ErrNotFound) {
return fmt.Errorf("Failed removing logical switch port: %w", err)
}
}
// Apply baseline ACL rules to internal logical switch.
dnsServers := []net.IP{}
if uplinkNet != nil {
dnsServers = append(dnsServers, dnsIPv4...)
dnsServers = append(dnsServers, dnsIPv6...)
}
err = acl.OVNApplyNetworkBaselineRules(n.ovnnb, n.getIntSwitchName(), n.getIntSwitchRouterPortName(), intRouterIPs, dnsServers)
if err != nil {
return fmt.Errorf("Failed applying baseline ACL rules to internal switch: %w", err)
}
// Create network port group if needed.
err = n.ensureNetworkPortGroup(projectID)
if err != nil {
return fmt.Errorf("Failed to setup network port group: %w", err)
}
// Ensure any network assigned security ACL port groups are created ready for instance NICs to use.
securityACLS := util.SplitNTrimSpace(n.config["security.acls"], ",", -1, true)
if len(securityACLS) > 0 {
var aclNameIDs map[string]int64
err := n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
var err error
// Get map of ACL names to DB IDs (used for generating OVN port group names).
acls, err := dbCluster.GetNetworkACLs(ctx, tx.Tx(), dbCluster.NetworkACLFilter{Project: &n.project})
if err != nil {
return err
}
aclNameIDs = make(map[string]int64, len(acls))
for _, acl := range acls {
aclNameIDs[acl.Name] = int64(acl.ID)
}
return nil
})
if err != nil {
return fmt.Errorf("Failed getting network ACL IDs for security ACL setup: %w", err)
}
// Request our network is setup with the specified ACLs.
aclNets := map[string]acl.NetworkACLUsage{
n.Name(): {Name: n.Name(), Type: n.Type(), ID: n.ID(), Config: n.Config()},
}
cleanup, err := acl.OVNEnsureACLs(n.state, n.logger, n.ovnnb, n.Project(), aclNameIDs, aclNets, securityACLS, false)
if err != nil {
return fmt.Errorf("Failed ensuring security ACLs are configured in OVN for network: %w", err)
}
reverter.Add(cleanup)
}
reverter.Success()
return nil
}
func (n *ovn) getDhcpOptionUUIDs() (v4Uuid networkOVN.OVNDHCPOptionsUUID, v6Uuid networkOVN.OVNDHCPOptionsUUID, err error) {
// Find first existing DHCP options set for IPv4 and IPv6 and update them instead of adding sets.
existingOpts, err := n.ovnnb.GetLogicalSwitchDHCPOptions(context.TODO(), n.getIntSwitchName())
if err != nil {
return "", "", fmt.Errorf("Failed getting existing DHCP settings for internal switch: %w", err)
}
for _, existingOpt := range existingOpts {
if existingOpt.CIDR.IP.To4() == nil {
if v6Uuid != "" {
return "", "", fmt.Errorf("Multiple matching DHCPv6 option sets found for switch %q", n.getIntSwitchName())
}
v6Uuid = existingOpt.UUID
} else {
if v4Uuid != "" {
return "", "", fmt.Errorf("Multiple matching DHCPv4 option sets found for switch %q", n.getIntSwitchName())
}
v4Uuid = existingOpt.UUID
}
}
return v4Uuid, v6Uuid, nil
}
// logicalRouterPolicySetup applies the security policy to the logical router (clearing any existing policies).
// Optionally excludePeers takes a list of peer network IDs to exclude from the router policy. This is useful
// when removing a peer connection as it allows the security policy to be removed from OVN for that peer before the
// peer connection has been removed from the database.
func (n *ovn) logicalRouterPolicySetup(ovnnb *networkOVN.NB, excludePeers ...int64) error {
extRouterPort := n.getRouterExtPortName()
intRouterPort := n.getRouterIntPortName()
addrSetPrefix := acl.OVNIntSwitchPortGroupAddressSetPrefix(n.ID())
policies := []networkOVN.OVNRouterPolicy{
{
// Allow IPv6 packets arriving from internal router port with valid source address.
Priority: ovnRouterPolicyPeerAllowPriority,
Match: fmt.Sprintf(`(inport == "%s" && ip6 && ip6.src == $%s_ip6)`, intRouterPort, addrSetPrefix),
Action: "allow",
},
{
// Allow IPv4 packets arriving from internal router port with valid source address.
Priority: ovnRouterPolicyPeerAllowPriority,
Match: fmt.Sprintf(`(inport == "%s" && ip4 && ip4.src == $%s_ip4)`, intRouterPort, addrSetPrefix),
Action: "allow",
},
{
// Drop all other traffic arriving from internal router port.
// This prevents packets with a source address that is not valid to be dropped, and ensures
// that we can use the internal address set in ACL rules and trust that this represents all
// possible routed traffic from the internal network.
Priority: ovnRouterPolicyPeerDropPriority,
Match: fmt.Sprintf(`(inport == "%s")`, intRouterPort),
Action: "drop",
},
}
// Add rules to drop inbound traffic arriving on external uplink port from peer connection addresses.
// This prevents source address spoofing of peer connection routes from the external network, which in
// turn allows us to use the peer connection's address set for referencing traffic from the peer in ACL.
err := n.forPeers(func(targetOVNNet *ovn) error {
if slices.Contains(excludePeers, targetOVNNet.ID()) {
return nil // Don't setup rules for this peer network connection.
}
targetAddrSetPrefix := acl.OVNIntSwitchPortGroupAddressSetPrefix(targetOVNNet.ID())
// Associate the rules with the local peering port so we can identify them later if needed.
comment := n.getLogicalRouterPeerPortName(targetOVNNet.ID())
policies = append(policies, networkOVN.OVNRouterPolicy{
Priority: ovnRouterPolicyPeerDropPriority,
Match: fmt.Sprintf(`(inport == "%s" && ip6 && ip6.src == $%s_ip6) // %s`, extRouterPort, targetAddrSetPrefix, comment),
Action: "drop",
}, networkOVN.OVNRouterPolicy{
Priority: ovnRouterPolicyPeerDropPriority,
Match: fmt.Sprintf(`(inport == "%s" && ip4 && ip4.src == $%s_ip4) // %s`, extRouterPort, targetAddrSetPrefix, comment),
Action: "drop",
})
return nil
})
if err != nil {
return err
}
return n.ovnnb.UpdateLogicalRouterPolicy(context.TODO(), n.getRouterName(), policies...)
}
// ensureNetworkPortGroup ensures that the network level port group (used for classifying NICs connected to this
// network as internal) exists.
func (n *ovn) ensureNetworkPortGroup(projectID int64) error {
// Create port group (if needed) for NICs to classify as internal.
intPortGroupName := acl.OVNIntSwitchPortGroupName(n.ID())
intPortGroupUUID, _, err := n.ovnnb.GetPortGroupInfo(context.TODO(), intPortGroupName)
if err != nil {
return fmt.Errorf("Failed getting port group UUID for network %q setup: %w", n.Name(), err)
}
if intPortGroupUUID == "" {
// Create internal port group and associate it with the logical switch, so that it will be
// removed when the logical switch is removed.
err = n.ovnnb.CreatePortGroup(context.TODO(), projectID, intPortGroupName, "", n.getIntSwitchName())
if err != nil {
return fmt.Errorf("Failed creating port group %q for network %q setup: %w", intPortGroupName, n.Name(), err)
}
}
return nil
}
// addChassisGroupEntry adds an entry for the local OVS chassis to the OVN logical network's chassis group.
// The chassis priority value is a stable-random value derived from chassis group name and node ID. This is so we
// don't end up using the same chassis for the primary uplink chassis for all OVN networks in a cluster.
func (n *ovn) addChassisGroupEntry() error {
// Get local chassis ID for chassis group.
vswitch, err := n.state.OVS()
if err != nil {
return fmt.Errorf("Failed to connect to OVS: %w", err)
}
chassisID, err := vswitch.GetChassisID(context.TODO())
if err != nil {
return fmt.Errorf("Failed getting OVS Chassis ID: %w", err)
}
// Seed the stable random number generator with the chassis group name.
// This way each OVN network will have its own random seed, so that we don't end up using the same chassis
// for the primary uplink chassis for all OVN networks in a cluster.
chassisGroupName := n.getChassisGroupName()
r, err := localUtil.GetStableRandomGenerator(string(chassisGroupName))
if err != nil {
return fmt.Errorf("Failed generating stable random chassis group priority: %w", err)
}
// Get all members in cluster.
ourMemberID := int(n.state.DB.Cluster.GetNodeID())
var memberIDs []int
err = n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
members, err := tx.GetNodes(ctx)
if err != nil {
return fmt.Errorf("Failed getting cluster members for adding chassis group entry: %w", err)
}
for _, member := range members {
memberIDs = append(memberIDs, int(member.ID))
}
return nil
})
if err != nil {
return err
}
// Sort the nodes based on ID for stable priority generation.
sort.Ints(memberIDs)
// Generate a random priority from the seed for each node until we find a match for our node ID.
// In this way the chassis priority for this node will be set to a per-node stable random value.
var priority int
for _, memberID := range memberIDs {
priority = r.Intn(ovnChassisPriorityMax + 1)
if memberID == ourMemberID {
break
}
}
err = n.ovnnb.SetChassisGroupPriority(context.TODO(), chassisGroupName, chassisID, priority)
if err != nil {
return fmt.Errorf("Failed adding OVS chassis %q with priority %d to chassis group %q: %w", chassisID, priority, chassisGroupName, err)
}
n.logger.Debug("Chassis group entry added", logger.Ctx{"chassisGroup": chassisGroupName, "memberID": ourMemberID, "priority": priority})
return nil
}
// deleteChassisGroupEntry deletes an entry for the local OVS chassis from the OVN logical network's chassis group.
func (n *ovn) deleteChassisGroupEntry() error {
// Remove local chassis from chassis group.
vswitch, err := n.state.OVS()
if err != nil {
return fmt.Errorf("Failed to connect to OVS: %w", err)
}
chassisID, err := vswitch.GetChassisID(context.TODO())
if err != nil {
return fmt.Errorf("Failed getting OVS Chassis ID: %w", err)
}
err = n.ovnnb.SetChassisGroupPriority(context.TODO(), n.getChassisGroupName(), chassisID, -1)
if err != nil && !errors.Is(err, ovs.ErrNotFound) {
return fmt.Errorf("Failed deleting OVS chassis %q from chassis group %q: %w", chassisID, n.getChassisGroupName(), err)
}
return nil
}
// Delete deletes a network.
func (n *ovn) Delete(clientType request.ClientType) error {
n.logger.Debug("Delete", logger.Ctx{"clientType": clientType})
err := n.Stop()
if err != nil {
return err
}
if clientType == request.ClientTypeNormal {
// Delete the router and anything tied to it (router ports, static routes, policies, nat, ...).
err = n.ovnnb.DeleteLogicalRouter(context.TODO(), n.getRouterName())
if err != nil && !errors.Is(err, networkOVN.ErrNotFound) {
return err
}
// Delete the external logical switch and anything tied to it (ports, ...).
err = n.ovnnb.DeleteLogicalSwitch(context.TODO(), n.getExtSwitchName())
if err != nil && !errors.Is(err, networkOVN.ErrNotFound) {
return err
}
// Delete the internal logical switch and anything tied to it (ports, ...).
err = n.ovnnb.DeleteLogicalSwitch(context.TODO(), n.getIntSwitchName())
if err != nil && !errors.Is(err, networkOVN.ErrNotFound) {
return err
}
// Delete any related address sets.
err = n.ovnnb.DeleteAddressSet(context.TODO(), acl.OVNIntSwitchPortGroupAddressSetPrefix(n.ID()))
if err != nil && !errors.Is(err, networkOVN.ErrNotFound) {
return err
}
// Delete the chassis group for the network.
err = n.ovnnb.DeleteChassisGroup(context.TODO(), n.getChassisGroupName())
if err != nil && !errors.Is(err, networkOVN.ErrNotFound) {
return err
}
// Clean up any now unused port group.
securityACLs := util.SplitNTrimSpace(n.config["security.acls"], ",", -1, true)
if len(securityACLs) > 0 {
err = acl.OVNPortGroupDeleteIfUnused(n.state, n.logger, n.ovnnb, n.project, &api.Network{Name: n.name}, "")
if err != nil {
return fmt.Errorf("Failed removing unused OVN port groups: %w", err)
}
}
// Delete any network forwards and load balancers.
forwardListenAddresses := map[int64]string{}
loadBalancerListenAddresses := map[int64]string{}
err = n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
networkID := n.ID()
// Get the forward addresses.
dbForwards, err := dbCluster.GetNetworkForwards(ctx, tx.Tx(), dbCluster.NetworkForwardFilter{
NetworkID: &networkID,
})
if err != nil {
return fmt.Errorf("Failed loading network forwards: %w", err)
}
// Get the load balancers.
dbLoadBalancers, err := dbCluster.GetNetworkLoadBalancers(ctx, tx.Tx(), dbCluster.NetworkLoadBalancerFilter{
NetworkID: &networkID,
})
if err != nil {
return fmt.Errorf("Failed loading network load balancers: %w", err)
}
for _, fwd := range dbForwards {
forwardListenAddresses[fwd.ID] = fwd.ListenAddress
}
for _, lb := range dbLoadBalancers {
loadBalancerListenAddresses[lb.ID] = lb.ListenAddress
}
return nil
})
if err != nil {
return err
}
loadBalancers := make([]networkOVN.OVNLoadBalancer, 0, len(forwardListenAddresses)+len(loadBalancerListenAddresses))
for _, listenAddress := range forwardListenAddresses {
loadBalancers = append(loadBalancers, n.getLoadBalancerName(listenAddress))
}
for _, listenAddress := range loadBalancerListenAddresses {
loadBalancers = append(loadBalancers, n.getLoadBalancerName(listenAddress))
}
err = n.ovnnb.DeleteLoadBalancer(context.TODO(), loadBalancers...)
if err != nil {
return fmt.Errorf("Failed deleting network forwards and load balancers: %w", err)
}
}
return n.common.delete(clientType)
}
// Rename renames a network.
func (n *ovn) Rename(newName string) error {
n.logger.Debug("Rename", logger.Ctx{"newName": newName})
// Rename common steps.
err := n.common.rename(newName)
if err != nil {
return err
}
return nil
}
// chassisEnabled checks the cluster config to see if this particular
// member should act as an OVN chassis.
func (n *ovn) chassisEnabled(ctx context.Context, tx *db.ClusterTx) (bool, error) {
// Get the member info.
memberID := tx.GetNodeID()
members, err := tx.GetNodes(ctx)
if err != nil {
return false, fmt.Errorf("Failed getting cluster members: %w", err)
}
// Determine whether to add ourselves as a chassis.
// If no server has the role, enable the chassis, otherwise only
// enable if the local server has the role.
enableChassis := -1
for _, member := range members {
hasRole := slices.Contains(member.Roles, db.ClusterRoleOVNChassis)
if hasRole {
if member.ID == memberID {
// Local node has the OVN chassis role, enable chassis.
enableChassis = 1
break
}
// Some other node has the OVN chassis role, don't enable.
enableChassis = 0
}
}
return enableChassis != 0, nil
}
// Start starts adds the local OVS chassis ID to the OVN chass group and starts the local OVS uplink port.
func (n *ovn) Start() error {
n.logger.Debug("Start")
reverter := revert.New()
defer reverter.Fail()
var err error
reverter.Add(func() { n.setUnavailable() })
// Check that uplink network is available.
if n.config["network"] != "" && n.config["network"] != "none" && !IsAvailable(api.ProjectDefaultName, n.config["network"]) {
return fmt.Errorf("Uplink network %q is unavailable", n.config["network"])
}
var projectID int64
var chassisEnabled bool
err = n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
// Get the project ID.
projectID, err = dbCluster.GetProjectID(context.Background(), tx.Tx(), n.project)
if err != nil {
return err
}
// Check if we should enable the chassis.
chassisEnabled, err = n.chassisEnabled(ctx, tx)
if err != nil {
return err
}
return nil
})
if err != nil {
return fmt.Errorf("Failed getting project ID for project %q: %w", n.project, err)
}
// Ensure network level port group exists.
err = n.ensureNetworkPortGroup(projectID)
if err != nil {
return err
}
// Handle chassis groups.
if chassisEnabled {
// Add local member's OVS chassis ID to logical chassis group.
err = n.addChassisGroupEntry()
if err != nil {
return err
}
} else {
// Make sure we don't have a group entry.
err = n.deleteChassisGroupEntry()
if err != nil {
return err
}
}
err = n.startUplinkPort()
if err != nil {
return err
}
// Setup BGP.
err = n.bgpSetup(nil)
if err != nil {
return err
}
err = n.loadBalancerBGPSetupPrefixes()
if err != nil {
return fmt.Errorf("Failed applying BGP prefixes for load balancers: %w", err)
}
// Setup event handler for monitored services.
handler := networkOVN.EventHandler{
Tables: []string{"Service_Monitor"},
Hook: func(action string, table string, oldObject ovsdbModel.Model, newObject ovsdbModel.Model) {
// Skip invalid notifications.
if oldObject == nil && newObject == nil {
return
}
// Get the object.
dbObject := newObject
if dbObject == nil {
dbObject = oldObject
}
srvStatus, ok := dbObject.(*ovnSB.ServiceMonitor)
if !ok {
return
}
// Check if this is our network.
if !strings.HasPrefix(srvStatus.LogicalPort, fmt.Sprintf("incus-net%d-instance-", n.id)) {
return
}
// Locate affected load-balancers.
lbs, err := n.ovnnb.GetLoadBalancersByStatusUpdate(context.TODO(), *srvStatus)
if err != nil {
return
}
for _, lb := range lbs {
// Check for status of all backends on this load-balancer.
online, err := n.ovnsb.CheckLoadBalancerOnline(context.TODO(), lb)
if err != nil {
return
}
// Parse the name.
fields := strings.Split(lb.Name, "-")
listenAddr := net.ParseIP(fields[3])
if listenAddr == nil {
return
}
// Check if we have a matching UDP load-balancer.
fields[4] = "udp"
lbUDP, _ := n.ovnnb.GetLoadBalancer(context.TODO(), networkOVN.OVNLoadBalancer(strings.Join(fields, "-")))
if lbUDP != nil {
// UDP backends can't be checked, so have to assume online.
online = true
}
// Prepare advertisement.
ipVersion := uint(4)
if listenAddr.To4() == nil {
ipVersion = 6
}
bgpOwner := fmt.Sprintf("network_%d_load_balancer", n.id)
nextHopAddr := n.bgpNextHopAddress(ipVersion)
natEnabled := util.IsTrue(n.config[fmt.Sprintf("ipv%d.nat", ipVersion)])
_, netSubnet, _ := net.ParseCIDR(n.config[fmt.Sprintf("ipv%d.address", ipVersion)])
routeSubnetSize := 128
if ipVersion == 4 {
routeSubnetSize = 32
}
// Don't export internal address forwards (those inside the NAT enabled network's subnet).
if natEnabled && netSubnet != nil && netSubnet.Contains(listenAddr) {
return
}
_, ipRouteSubnet, err := net.ParseCIDR(fmt.Sprintf("%s/%d", listenAddr.String(), routeSubnetSize))
if err != nil {
return
}
// Update the BGP state.
if online {
err = n.state.BGP.AddPrefix(*ipRouteSubnet, nextHopAddr, bgpOwner)
if err != nil {
return
}
} else {
err = n.state.BGP.RemovePrefix(*ipRouteSubnet, nextHopAddr)
if err != nil {
return
}
}
}
},
}
err = networkOVN.AddOVNSBHandler(fmt.Sprintf("network_%d", n.id), handler)
if err != nil {
return err
}
reverter.Success()
// Ensure network is marked as available now its started.
n.setAvailable()
return nil
}
// Stop deletes the local OVS uplink port (if unused) and deletes the local OVS chassis ID from the
// OVN chassis group.
func (n *ovn) Stop() error {
n.logger.Debug("Stop")
// Delete local OVS chassis ID from logical OVN HA chassis group.
err := n.deleteChassisGroupEntry()
if err != nil {
return err
}
// Delete local uplink port if not used by other OVN networks.
err = n.deleteUplinkPort()
if err != nil {
return err
}
// Clear BGP.
err = n.bgpClear(n.config)
if err != nil {
return err
}
// Clear event handler for monitored services.
err = networkOVN.RemoveOVNSBHandler(fmt.Sprintf("network_%d", n.id))
if err != nil {
return err
}
return nil
}
// instanceNICGetRoutes returns list of routes defined in nicConfig.
func (n *ovn) instanceNICGetRoutes(nicConfig map[string]string) []net.IPNet {
var routes []net.IPNet
routeKeys := []string{"ipv4.routes", "ipv4.routes.external", "ipv6.routes", "ipv6.routes.external"}
for _, key := range routeKeys {
for _, routeStr := range util.SplitNTrimSpace(nicConfig[key], ",", -1, true) {
_, route, err := net.ParseCIDR(routeStr)
if err != nil {
continue // Skip invalid routes (should never happen).
}
routes = append(routes, *route)
}
}
return routes
}
// Update updates the network. Accepts notification boolean indicating if this update request is coming from a
// cluster notification, in which case do not update the database, just apply local changes needed.
func (n *ovn) Update(newNetwork api.NetworkPut, targetNode string, clientType request.ClientType) error {
n.logger.Debug("Update", logger.Ctx{"clientType": clientType, "newNetwork": newNetwork})
err := n.populateAutoConfig(newNetwork.Config)
if err != nil {
return fmt.Errorf("Failed generating auto config: %w", err)
}
if clientType == request.ClientTypeNotifier {
// Reload BGP on notifications.
err = n.bgpSetup(nil)
if err != nil {
return err
}
err = n.loadBalancerBGPSetupPrefixes()
if err != nil {
return fmt.Errorf("Failed applying BGP prefixes for load balancers: %w", err)
}
return nil
}
dbUpdateNeeded, changedKeys, oldNetwork, err := n.common.configChanged(newNetwork)
if err != nil {
return err
}
if !dbUpdateNeeded {
return nil // Nothing changed.
}
// If the network as a whole has not had any previous creation attempts, or the node itself is still
// pending, then don't apply the new settings to the node, just to the database record (ready for the
// actual global create request to be initiated).
if n.Status() == api.NetworkStatusPending || n.LocalStatus() == api.NetworkStatusPending {
return n.common.update(newNetwork, targetNode, clientType)
}
reverter := revert.New()
defer reverter.Fail()
// Define a function which reverts everything.
reverter.Add(func() {
// Reset changes to all nodes and database.
_ = n.common.update(oldNetwork, targetNode, clientType)
// Reset any change that was made to logical network.
if clientType == request.ClientTypeNormal {
_ = n.setup(true)
}
_ = n.Start()
})
// Stop network before new config applied if uplink network is changing.
if slices.Contains(changedKeys, "network") {
err = n.Stop()
if err != nil {
return err
}
// Remove volatile keys associated with old network in new config.
delete(newNetwork.Config, ovnVolatileUplinkIPv4)
delete(newNetwork.Config, ovnVolatileUplinkIPv6)
}
// Apply changes to all nodes and database.
err = n.common.update(newNetwork, targetNode, clientType)
if err != nil {
return err
}
// Re-setup the logical network after config applied if needed.
if len(changedKeys) > 0 && clientType == request.ClientTypeNormal {
err = n.setup(true)
if err != nil {
return err
}
// Work out which ACLs have been added and removed.
oldACLs := util.SplitNTrimSpace(oldNetwork.Config["security.acls"], ",", -1, true)
newACLs := util.SplitNTrimSpace(newNetwork.Config["security.acls"], ",", -1, true)
removedACLs := []string{}
for _, oldACL := range oldACLs {
if !slices.Contains(newACLs, oldACL) {
removedACLs = append(removedACLs, oldACL)
}
}
addedACLs := []string{}
for _, newACL := range newACLs {
if !slices.Contains(oldACLs, newACL) {
addedACLs = append(addedACLs, newACL)
}
}
// Detect if network default rule config has changed.
defaultRuleKeys := []string{"security.acls.default.ingress.action", "security.acls.default.egress.action", "security.acls.default.ingress.logged", "security.acls.default.egress.logged"}
changedDefaultRuleKeys := []string{}
for _, k := range defaultRuleKeys {
if slices.Contains(changedKeys, k) {
changedDefaultRuleKeys = append(changedDefaultRuleKeys, k)
}
}
var aclNameIDs map[string]int64
err = n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
// Get map of ACL names to DB IDs (used for generating OVN port group names).
acls, err := dbCluster.GetNetworkACLs(ctx, tx.Tx(), dbCluster.NetworkACLFilter{Project: &n.project})
if err != nil {
return err
}
aclNameIDs = make(map[string]int64, len(acls))
for _, acl := range acls {
aclNameIDs[acl.Name] = int64(acl.ID)
}
return nil
})
if err != nil {
return fmt.Errorf("Failed getting network ACL IDs for security ACL update: %w", err)
}
addChangeSet := map[networkOVN.OVNPortGroup][]networkOVN.OVNSwitchPortUUID{}
removeChangeSet := map[networkOVN.OVNPortGroup][]networkOVN.OVNSwitchPortUUID{}
// Get list of active switch ports (avoids repeated querying of OVN NB).
activePorts, err := n.ovnnb.GetLogicalSwitchPorts(context.TODO(), n.getIntSwitchName())
if err != nil {
return fmt.Errorf("Failed getting active ports: %w", err)
}
aclConfigChanged := len(addedACLs) > 0 || len(removedACLs) > 0 || len(changedDefaultRuleKeys) > 0
var localNICRoutes []net.IPNet
// Apply ACL changes to running instance NICs that use this network.
err = UsedByInstanceDevices(n.state, n.Project(), n.Name(), n.Type(), func(inst db.InstanceArgs, nicName string, nicConfig map[string]string) error {
nicACLs := util.SplitNTrimSpace(nicConfig["security.acls"], ",", -1, true)
// Get logical port UUID and name.
instancePortName := n.getInstanceDevicePortName(inst.Config["volatile.uuid"], nicName)
portUUID, found := activePorts[instancePortName]
if !found {
return nil // No need to update a port that isn't started yet.
}
// Apply security ACL and default rule changes.
if aclConfigChanged {
// Check whether we need to add any of the new ACLs to the NIC.
for _, addedACL := range addedACLs {
if slices.Contains(nicACLs, addedACL) {
continue // NIC already has this ACL applied directly, so no need to add.
}
aclID, found := aclNameIDs[addedACL]
if !found {
return fmt.Errorf("Cannot find security ACL ID for %q", addedACL)
}
// Add NIC port to ACL port group.
portGroupName := acl.OVNACLPortGroupName(aclID)
acl.OVNPortGroupInstanceNICSchedule(portUUID, addChangeSet, portGroupName)
n.logger.Debug("Scheduled logical port for ACL port group addition", logger.Ctx{"networkACL": addedACL, "portGroup": portGroupName, "port": instancePortName})
}
// Check whether we need to remove any of the removed ACLs from the NIC.
for _, removedACL := range removedACLs {
if slices.Contains(nicACLs, removedACL) {
continue // NIC still has this ACL applied directly, so don't remove.
}
aclID, found := aclNameIDs[removedACL]
if !found {
return fmt.Errorf("Cannot find security ACL ID for %q", removedACL)
}
// Remove NIC port from ACL port group.
portGroupName := acl.OVNACLPortGroupName(aclID)
acl.OVNPortGroupInstanceNICSchedule(portUUID, removeChangeSet, portGroupName)
n.logger.Debug("Scheduled logical port for ACL port group removal", logger.Ctx{"networkACL": removedACL, "portGroup": portGroupName, "port": instancePortName})
}
// If there are no ACLs being applied to the NIC (either from network or NIC) then
// we should remove the default rule from the NIC.
if len(newACLs) <= 0 && len(nicACLs) <= 0 {
err = n.ovnnb.ClearPortGroupPortACLRules(context.TODO(), acl.OVNIntSwitchPortGroupName(n.ID()), instancePortName)
if err != nil {
return fmt.Errorf("Failed clearing OVN default ACL rules for instance NIC: %w", err)
}
n.logger.Debug("Cleared NIC default rules", logger.Ctx{"port": instancePortName})
} else {
defaultRuleChange := false
// If there are ACLs being applied, then decide if the default rule config
// has changed materially for the NIC and update it if needed.
for _, k := range changedDefaultRuleKeys {
_, found := nicConfig[k]
if found {
continue // Skip if changed key is overridden in NIC.
}
defaultRuleChange = true
break
}
// If the default rule config has changed materially for this NIC or the
// network previously didn't have any ACLs applied and now does, then add
// the default rule to the NIC.
if defaultRuleChange || len(oldACLs) <= 0 {
// Set the automatic default ACL rule for the port.
ingressAction, ingressLogged := n.instanceDeviceACLDefaults(nicConfig, "ingress")
egressAction, egressLogged := n.instanceDeviceACLDefaults(nicConfig, "egress")
logPrefix := fmt.Sprintf("%s-%s", inst.Config["volatile.uuid"], nicName)
err = acl.OVNApplyInstanceNICDefaultRules(n.ovnnb, acl.OVNIntSwitchPortGroupName(n.ID()), logPrefix, instancePortName, ingressAction, ingressLogged, egressAction, egressLogged)
if err != nil {
return fmt.Errorf("Failed applying OVN default ACL rules for instance NIC: %w", err)
}
n.logger.Debug("Set NIC default rule", logger.Ctx{"port": instancePortName, "ingressAction": ingressAction, "ingressLogged": ingressLogged, "egressAction": egressAction, "egressLogged": egressLogged})
}
}
}
// Add NIC routes to list.
localNICRoutes = append(localNICRoutes, n.instanceNICGetRoutes(nicConfig)...)
return nil
})
if err != nil {
return err
}
// Apply add/remove changesets.
if len(addChangeSet) > 0 || len(removeChangeSet) > 0 {
n.logger.Debug("Applying ACL port group member change sets")
err = n.ovnnb.UpdatePortGroupMembers(context.TODO(), addChangeSet, removeChangeSet)
if err != nil {
return fmt.Errorf("Failed applying OVN port group member change sets for instance NIC: %w", err)
}
}
// Check if any of the removed ACLs should have any unused port groups deleted.
if len(removedACLs) > 0 {
err = acl.OVNPortGroupDeleteIfUnused(n.state, n.logger, n.ovnnb, n.project, &api.Network{Name: n.name}, "", newACLs...)
if err != nil {
return fmt.Errorf("Failed removing unused OVN port groups: %w", err)
}
}
// Ensure all active NIC routes are present in internal switch's address set.
err = n.ovnnb.UpdateAddressSetAdd(context.TODO(), acl.OVNIntSwitchPortGroupAddressSetPrefix(n.ID()), localNICRoutes...)
if err != nil {
return fmt.Errorf("Failed adding active NIC routes to switch address set: %w", err)
}
// Remove any old unused subnet addresses from the internal switch's address set.
rebuildPeers := false
for _, key := range []string{"ipv4.address", "ipv6.address"} {
if slices.Contains(changedKeys, key) {
rebuildPeers = true
_, oldRouterIntPortIPNet, _ := net.ParseCIDR(oldNetwork.Config[key])
if oldRouterIntPortIPNet != nil {
err = n.ovnnb.UpdateAddressSetRemove(context.TODO(), acl.OVNIntSwitchPortGroupAddressSetPrefix(n.ID()), *oldRouterIntPortIPNet)
if err != nil {
return fmt.Errorf("Failed removing old network subnet %q from switch address set: %w", oldRouterIntPortIPNet.String(), err)
}
}
}
}
if rebuildPeers {
// Rebuild peering config.
opts, err := n.peerGetLocalOpts(localNICRoutes)
if err != nil {
return err
}
err = n.forPeers(func(targetOVNNet *ovn) error {
err = n.peerSetup(n.ovnnb, targetOVNNet, *opts)
if err != nil {
return err
}
return nil
})
if err != nil {
return err
}
}
}
// If uplink network is changing, start network after config applied.
if slices.Contains(changedKeys, "network") {
err = n.Start()
if err != nil {
return err
}
// Notify all other members to refresh their BGP prefixes.
notifier, err := cluster.NewNotifier(n.state, n.state.Endpoints.NetworkCert(), n.state.ServerCert(), cluster.NotifyAll)
if err != nil {
return err
}
err = notifier(func(client incus.InstanceServer) error {
return client.UseProject(n.project).UpdateNetwork(n.name, newNetwork, "")
})
if err != nil {
return err
}
} else {
// Setup BGP.
err = n.bgpSetup(oldNetwork.Config)
if err != nil {
return err
}
}
err = n.loadBalancerBGPSetupPrefixes()
if err != nil {
return fmt.Errorf("Failed applying BGP prefixes for load balancers: %w", err)
}
reverter.Success()
return nil
}
// getInstanceDevicePortName returns the switch port name to use for an instance device.
func (n *ovn) getInstanceDevicePortName(instanceUUID string, deviceName string) networkOVN.OVNSwitchPort {
return networkOVN.OVNSwitchPort(fmt.Sprintf("%s-%s-%s", n.getIntSwitchInstancePortPrefix(), instanceUUID, deviceName))
}
// instanceDevicePortRoutesParse parses the instance NIC device config for internal routes and external routes.
func (n *ovn) instanceDevicePortRoutesParse(deviceConfig map[string]string) ([]*net.IPNet, []*net.IPNet, error) {
var err error
internalRoutes := []*net.IPNet{}
for _, key := range []string{"ipv4.routes", "ipv6.routes"} {
if deviceConfig[key] == "" {
continue
}
internalRoutes, err = SubnetParseAppend(internalRoutes, util.SplitNTrimSpace(deviceConfig[key], ",", -1, false)...)
if err != nil {
return nil, nil, fmt.Errorf("Invalid %q value: %w", key, err)
}
}
externalRoutes := []*net.IPNet{}
for _, key := range []string{"ipv4.routes.external", "ipv6.routes.external"} {
if deviceConfig[key] == "" {
continue
}
externalRoutes, err = SubnetParseAppend(externalRoutes, util.SplitNTrimSpace(deviceConfig[key], ",", -1, false)...)
if err != nil {
return nil, nil, fmt.Errorf("Invalid %q value: %w", key, err)
}
}
return internalRoutes, externalRoutes, nil
}
// InstanceDevicePortValidateExternalRoutes validates the external routes for an OVN instance port.
func (n *ovn) InstanceDevicePortValidateExternalRoutes(deviceInstance instance.Instance, deviceName string, portExternalRoutes []*net.IPNet) error {
if n.config["network"] == "none" {
return nil
}
var p *api.Project
var uplink *api.Network
err := n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
var err error
// Get uplink routes.
_, uplink, _, err = tx.GetNetworkInAnyState(ctx, api.ProjectDefaultName, n.config["network"])
return err
})
if err != nil {
return fmt.Errorf("Failed to load uplink network %q: %w", n.config["network"], err)
}
// Check port's external routes are sufficiently small when using l2proxy ingress mode on uplink.
if slices.Contains([]string{"l2proxy", ""}, uplink.Config["ovn.ingress_mode"]) {
for _, portExternalRoute := range portExternalRoutes {
rOnes, rBits := portExternalRoute.Mask.Size()
if rBits > 32 && rOnes < 122 {
return fmt.Errorf("External route %q is too large. Maximum size for IPv6 external route is /122", portExternalRoute.String())
} else if rOnes < 26 {
return fmt.Errorf("External route %q is too large. Maximum size for IPv4 external route is /26", portExternalRoute.String())
}
}
}
// Load the project to get uplink network restrictions.
err = n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
project, err := dbCluster.GetProject(ctx, tx.Tx(), n.project)
if err != nil {
return err
}
p, err = project.ToAPI(ctx, tx.Tx())
return err
})
if err != nil {
return fmt.Errorf("Failed to load network restrictions from project %q: %w", n.project, err)
}
externalSubnetsInUse, err := n.getExternalSubnetInUse(n.config["network"])
if err != nil {
return err
}
// Get project restricted routes.
projectRestrictedSubnets, err := n.projectRestrictedSubnets(p, n.config["network"])
if err != nil {
return err
}
// Check if uplink has routed ingress anycast mode enabled, as this relaxes the overlap checks.
ipv4UplinkAnycast := n.uplinkHasIngressRoutedAnycastIPv4(uplink)
ipv6UplinkAnycast := n.uplinkHasIngressRoutedAnycastIPv6(uplink)
for _, portExternalRoute := range portExternalRoutes {
// Check the external port route is allowed within both the uplink's external routes and any
// project restricted subnets.
err = n.validateExternalSubnet(uplink, projectRestrictedSubnets, portExternalRoute)
if err != nil {
return err
}
// Skip overlap checks if the external route's protocol has anycast mode enabled on the uplink.
if portExternalRoute.IP.To4() == nil {
if ipv6UplinkAnycast {
continue
}
} else if ipv4UplinkAnycast {
continue
}
// Check the external port route doesn't fall within any existing OVN network external subnets.
for _, externalSubnetUser := range externalSubnetsInUse {
// Skip our own network's SNAT address (as it can be used for NICs in the network).
if externalSubnetUser.usageType == subnetUsageNetworkSNAT && externalSubnetUser.networkProject == n.project && externalSubnetUser.networkName == n.name {
continue
}
if deviceInstance == nil {
// Skip checking instance devices during profile validation, only do this when
// an instance is supplied.
if externalSubnetUser.instanceDevice != "" {
continue
}
} else {
// Skip our own NIC device.
if externalSubnetUser.instanceProject == deviceInstance.Project().Name && externalSubnetUser.instanceName == deviceInstance.Name() && externalSubnetUser.instanceDevice == deviceName {
continue
}
}
if SubnetContains(&externalSubnetUser.subnet, portExternalRoute) || SubnetContains(portExternalRoute, &externalSubnetUser.subnet) {
// This error is purposefully vague so that it doesn't reveal any names of
// resources potentially outside of the network's project.
return fmt.Errorf("External subnet %q overlaps with another network or NIC", portExternalRoute.String())
}
}
}
return nil
}
// InstanceDevicePortAdd adds empty DNS record (to indicate port has been added) and any DHCP reservations for
// instance device port.
func (n *ovn) InstanceDevicePortAdd(instanceUUID string, deviceName string, deviceConfig deviceConfig.Device) error {
instancePortName := n.getInstanceDevicePortName(instanceUUID, deviceName)
reverter := revert.New()
defer reverter.Fail()
dnsUUID, err := n.ovnnb.UpdateLogicalSwitchPortDNS(context.TODO(), n.getIntSwitchName(), instancePortName, "", nil)
if err != nil {
return fmt.Errorf("Failed adding DNS record: %w", err)
}
reverter.Add(func() {
_ = n.ovnnb.DeleteLogicalSwitchPortDNS(context.TODO(), n.getIntSwitchName(), dnsUUID, true)
})
// If NIC has static IPv4 address then create a DHCPv4 reservation.
if deviceConfig["ipv4.address"] != "" {
ip := net.ParseIP(deviceConfig["ipv4.address"])
if ip != nil {
dhcpReservations, err := n.ovnnb.GetLogicalSwitchDHCPv4Revervations(context.TODO(), n.getIntSwitchName())
if err != nil {
return fmt.Errorf("Failed getting DHCPv4 reservations: %w", err)
}
if !n.hasDHCPv4Reservation(dhcpReservations, ip) {
dhcpReservations = append(dhcpReservations, iprange.Range{Start: ip})
err = n.ovnnb.UpdateLogicalSwitchDHCPv4Revervations(context.TODO(), n.getIntSwitchName(), dhcpReservations)
if err != nil {
return fmt.Errorf("Failed adding DHCPv4 reservation for %q: %w", ip.String(), err)
}
}
}
}
reverter.Success()
return nil
}
// hasDHCPv4Reservation returns whether IP is in the supplied reservation list.
func (n *ovn) hasDHCPv4Reservation(dhcpReservations []iprange.Range, ip net.IP) bool {
for _, dhcpReservation := range dhcpReservations {
if dhcpReservation.Start.Equal(ip) && dhcpReservation.End == nil {
return true
}
}
return false
}
// InstanceDevicePortStart sets up an instance device port to the internal logical switch.
// Accepts a list of ACLs being removed from the NIC device (if called as part of a NIC update).
// Returns the logical switch port name and a list of IPs that were allocated to the port for DNS.
func (n *ovn) InstanceDevicePortStart(opts *OVNInstanceNICSetupOpts, securityACLsRemove []string) (networkOVN.OVNSwitchPort, []net.IP, error) {
if opts.InstanceUUID == "" {
return "", nil, errors.New("Instance UUID is required")
}
mac, err := net.ParseMAC(opts.DeviceConfig["hwaddr"])
if err != nil {
return "", nil, err
}
ipv4 := opts.DeviceConfig["ipv4.address"]
ipv6 := opts.DeviceConfig["ipv6.address"]
internalRoutes, externalRoutes, err := n.instanceDevicePortRoutesParse(opts.DeviceConfig)
if err != nil {
return "", nil, fmt.Errorf("Failed parsing NIC device routes: %w", err)
}
reverter := revert.New()
defer reverter.Fail()
// Get existing DHCPv4 static reservations.
// This is used for both checking sticky DHCPv4 allocation availability and for ensuring static DHCP
// reservations exist.
dhcpReservations, err := n.ovnnb.GetLogicalSwitchDHCPv4Revervations(context.TODO(), n.getIntSwitchName())
if err != nil {
return "", nil, fmt.Errorf("Failed getting DHCPv4 reservations: %w", err)
}
dhcpv4Subnet := n.DHCPv4Subnet()
dhcpv6Subnet := n.DHCPv6Subnet()
var dhcpV4UUID, dhcpV6UUID networkOVN.OVNDHCPOptionsUUID
if dhcpv4Subnet != nil || dhcpv6Subnet != nil {
dhcpV4UUID, dhcpV6UUID, err = n.getDhcpOptionUUIDs()
if err != nil {
return "", nil, err
}
}
if dhcpv4Subnet != nil {
if dhcpV4UUID == "" {
return "", nil, fmt.Errorf("Could not find DHCPv4 options for instance port for subnet %q", dhcpv4Subnet.String())
}
// If using dynamic IPv4, look for previously used sticky IPs from the NIC's last state.
var dhcpV4StickyIP net.IP
if opts.DeviceConfig["ipv4.address"] == "" {
for _, entry := range opts.LastStateIPs {
if entry.To4() != nil && SubnetContainsIP(dhcpv4Subnet, entry) {
dhcpV4StickyIP = entry
break
}
}
}
// If a previously used IP has been found and its not one of the static IPs, then check if
// the IP is available for use and if not then we can request this port use it statically.
if dhcpV4StickyIP != nil && dhcpV4StickyIP.String() != ipv4 {
// If the sticky IP isn't statically reserved, lets check its not used dynamically
// on any active port.
if !n.hasDHCPv4Reservation(dhcpReservations, dhcpV4StickyIP) {
existingPortIPs, err := n.ovnnb.GetLogicalSwitchIPs(context.TODO(), n.getIntSwitchName())
if err != nil {
return "", nil, fmt.Errorf("Failed getting existing switch port IPs: %w", err)
}
found := false
for _, ips := range existingPortIPs {
if IPInSlice(dhcpV4StickyIP, ips) {
found = true
break // IP is in use with another port, so cannot use it.
}
}
// If IP is not in use then request OVN use previously used IP for port.
if !found {
ipv4 = dhcpV4StickyIP.String()
}
}
}
}
if dhcpv6Subnet != nil {
if dhcpV6UUID == "" {
return "", nil, fmt.Errorf("Could not find DHCPv6 options for instance port for subnet %q", dhcpv6Subnet.String())
}
// If port isn't going to have fully dynamic IPs allocated by OVN, and instead only static
// IPv4 addresses have been added, then add an EUI64 static IPv6 address so that the switch
// port has an IPv6 address that will be used to generate a DNS record. This works around a
// limitation in OVN that prevents us requesting dynamic IPv6 address allocation when
// static IPv4 allocation is used.
if ipv4 != "" && ipv6 == "" {
eui64IP, err := eui64.ParseMAC(dhcpv6Subnet.IP, mac)
if err != nil {
return "", nil, fmt.Errorf("Failed generating EUI64 for instance port %q: %w", mac.String(), err)
}
// Add EUI64 as the IPv6 address.
ipv6 = eui64IP.String()
}
}
instancePortName := n.getInstanceDevicePortName(opts.InstanceUUID, opts.DeviceName)
var nestedPortParentName networkOVN.OVNSwitchPort
var nestedPortVLAN uint16
if opts.DeviceConfig["nested"] != "" {
nestedPortParentName = n.getInstanceDevicePortName(opts.InstanceUUID, opts.DeviceConfig["nested"])
nestedPortVLANInt64, err := strconv.ParseUint(opts.DeviceConfig["vlan"], 10, 16)
if err != nil {
return "", nil, fmt.Errorf("Invalid VLAN ID %q: %w", opts.DeviceConfig["vlan"], err)
}
nestedPortVLAN = uint16(nestedPortVLANInt64)
}
// Add port with mayExist set to true, so that if instance port exists, we don't fail and continue below
// to configure the port as needed. This is required in case the OVN northbound database was unavailable
// when the instance NIC was stopped and was unable to remove the port on last stop, which would otherwise
// prevent future NIC starts.
err = n.ovnnb.CreateLogicalSwitchPort(context.TODO(), n.getIntSwitchName(), instancePortName, &networkOVN.OVNSwitchPortOpts{
DHCPv4OptsID: dhcpV4UUID,
DHCPv6OptsID: dhcpV6UUID,
MAC: mac,
IPV4: ipv4,
IPV6: ipv6,
Parent: nestedPortParentName,
VLAN: nestedPortVLAN,
Location: n.state.ServerName,
Promiscuous: util.IsTrue(opts.DeviceConfig["security.promiscuous"]),
}, true)
if err != nil {
return "", nil, err
}
reverter.Add(func() {
_ = n.ovnnb.DeleteLogicalSwitchPort(context.TODO(), n.getIntSwitchName(), instancePortName)
})
// Add DNS records for port's IPs, and retrieve the IP addresses used.
var dnsIPv4, dnsIPv6 net.IP
dnsIPs := make([]net.IP, 0, 2)
// checkAndStoreIP checks if the supplied IP is valid and can be used for a missing DNS IP.
// If the found IP is needed, stores into the relevant dnsIPv{X} variable and into dnsIPs slice.
checkAndStoreIP := func(ip net.IP) {
if ip != nil {
isV4 := ip.To4() != nil
if dnsIPv4 == nil && isV4 {
dnsIPv4 = ip
} else if dnsIPv6 == nil && !isV4 {
dnsIPv6 = ip
}
dnsIPs = append(dnsIPs, ip)
}
}
// Populate DNS IP variables with any static IPs first before checking if we need to extract dynamic IPs.
for _, staticIP := range []string{ipv4, ipv6} {
if staticIP == "" || staticIP == "none" {
continue
}
checkAndStoreIP(net.ParseIP(staticIP))
}
// Apply device specific external address if any.
for _, keyPrefix := range []string{"ipv4", "ipv6"} {
// Check if the address is present.
value := opts.DeviceConfig[fmt.Sprintf("%s.address.external", keyPrefix)]
if value == "" {
continue
}
// Check if the family is configured.
if keyPrefix == "ipv4" && ipv4 == "" {
continue
}
if keyPrefix == "ipv6" && ipv6 == "" {
continue
}
// Parse the internal address.
var intNet *net.IPNet
if keyPrefix == "ipv4" {
_, intNet, err = net.ParseCIDR(fmt.Sprintf("%s/32", ipv4))
if err != nil {
return "", nil, fmt.Errorf("Invalid internal address %q: %w", ipv4, err)
}
} else {
_, intNet, err = net.ParseCIDR(fmt.Sprintf("%s/128", ipv6))
if err != nil {
return "", nil, fmt.Errorf("Invalid internal address %q: %w", ipv6, err)
}
}
// Parse the external address.
extIP := net.ParseIP(value)
if extIP == nil {
return "", nil, fmt.Errorf("Invalid external address %q", value)
}
if err := n.ovnnb.CreateLogicalRouterNAT(
context.TODO(),
n.getRouterName(),
"snat",
intNet,
extIP,
nil,
false,
true,
); err != nil {
return "", nil, fmt.Errorf("Failed to add SNAT %q: %w", value, err)
}
reverter.Add(func() {
_ = n.ovnnb.DeleteLogicalRouterNAT(
context.TODO(),
n.getRouterName(),
"snat",
false,
extIP,
)
})
}
// Get dynamic IPs for switch port if any IPs not assigned statically.
if (ipv4 != "none" && dnsIPv4 == nil) || (ipv6 != "none" && dnsIPv6 == nil) {
var dynamicIPs []net.IP
// Retry a few times in case port has not yet allocated dynamic IPs.
for range 40 {
dynamicIPs, err = n.ovnnb.GetLogicalSwitchPortDynamicIPs(context.TODO(), instancePortName)
if err == nil {
if len(dynamicIPs) > 0 {
break
}
} else if !errors.Is(err, ovsClient.ErrNotFound) {
return "", nil, err
}
time.Sleep(250 * time.Millisecond)
}
for _, dynamicIP := range dynamicIPs {
// Try and find the first IPv4 and IPv6 addresses from the dynamic address list.
checkAndStoreIP(dynamicIP)
}
// Check, after considering all dynamic IPs, whether we have got the required ones.
if (dnsIPv4 == nil && dhcpv4Subnet != nil) || (dnsIPv6 == nil && dhcpv6Subnet != nil) {
return "", nil, errors.New("Insufficient dynamic addresses allocated")
}
}
dnsName := fmt.Sprintf("%s.%s", opts.DNSName, n.getDomainName())
dnsUUID, err := n.ovnnb.UpdateLogicalSwitchPortDNS(context.TODO(), n.getIntSwitchName(), instancePortName, dnsName, dnsIPs)
if err != nil {
return "", nil, fmt.Errorf("Failed setting DNS for %q: %w", dnsName, err)
}
reverter.Add(func() {
_ = n.ovnnb.DeleteLogicalSwitchPortDNS(context.TODO(), n.getIntSwitchName(), dnsUUID, false)
})
// If NIC has static IPv4 address then ensure a DHCPv4 reservation exists.
// Do this at start time as well as add time in case an instance was copied (causing a duplicate address
// conflict at add time) which is later resolved by deleting the original instance, meaning a reservation needs to
// be added when the copied instance next starts.
if opts.DeviceConfig["ipv4.address"] != "" && dnsIPv4 != nil {
if !n.hasDHCPv4Reservation(dhcpReservations, dnsIPv4) {
dhcpReservations = append(dhcpReservations, iprange.Range{Start: dnsIPv4})
err = n.ovnnb.UpdateLogicalSwitchDHCPv4Revervations(context.TODO(), n.getIntSwitchName(), dhcpReservations)
if err != nil {
return "", nil, fmt.Errorf("Failed adding DHCPv4 reservation for %q: %w", dnsIPv4.String(), err)
}
}
}
// Publish NIC's IPs on uplink network if NAT is disabled and using l2proxy ingress mode on uplink.
if slices.Contains([]string{"l2proxy", ""}, opts.UplinkConfig["ovn.ingress_mode"]) {
for _, k := range []string{"ipv4.nat", "ipv6.nat"} {
if util.IsTrue(n.config[k]) {
continue
}
// Select the correct destination IP from the DNS records.
var ip net.IP
if k == "ipv4.nat" {
ip = dnsIPv4
} else if k == "ipv6.nat" {
ip = dnsIPv6
}
if ip == nil {
continue // No qualifying target IP from DNS records.
}
err = n.ovnnb.CreateLogicalRouterNAT(context.TODO(), n.getRouterName(), "dnat_and_snat", nil, ip, ip, true, true)
if err != nil {
return "", nil, err
}
reverter.Add(func() {
_ = n.ovnnb.DeleteLogicalRouterNAT(context.TODO(), n.getRouterName(), "dnat_and_snat", false, ip)
})
}
}
var routes []networkOVN.OVNRouterRoute
// In l3only mode we add the instance port's IPs as static routes to the router.
if util.IsTrue(n.config["ipv4.l3only"]) && dnsIPv4 != nil {
ipNet := IPToNet(dnsIPv4)
internalRoutes = append(internalRoutes, &ipNet)
}
if util.IsTrue(n.config["ipv6.l3only"]) && dnsIPv6 != nil {
ipNet := IPToNet(dnsIPv6)
internalRoutes = append(internalRoutes, &ipNet)
}
// Add each internal route (using the IPs set for DNS as target).
for _, internalRoute := range internalRoutes {
targetIP := dnsIPv4
if internalRoute.IP.To4() == nil {
targetIP = dnsIPv6
}
if targetIP == nil {
return "", nil, fmt.Errorf("Cannot add static route for %q as target IP is not set", internalRoute.String())
}
routes = append(routes, networkOVN.OVNRouterRoute{
Prefix: *internalRoute,
NextHop: targetIP,
Port: n.getRouterIntPortName(),
})
}
// Add each external route (using the IPs set for DNS as target).
for _, externalRoute := range externalRoutes {
targetIP := dnsIPv4
if externalRoute.IP.To4() == nil {
targetIP = dnsIPv6
}
if targetIP == nil {
return "", nil, fmt.Errorf("Cannot add static route for %q as target IP is not set", externalRoute.String())
}
routes = append(routes, networkOVN.OVNRouterRoute{
Prefix: *externalRoute,
NextHop: targetIP,
Port: n.getRouterIntPortName(),
})
// When using l2proxy ingress mode on uplink, in order to advertise the external route to the
// uplink network using proxy ARP/NDP we need to add a stateless dnat_and_snat rule (as to my
// knowledge this is the only way to get the OVN router to respond to ARP/NDP requests for IPs that
// it doesn't actually have). However we have to add each IP in the external route individually as
// DNAT doesn't support whole subnets.
if slices.Contains([]string{"l2proxy", ""}, opts.UplinkConfig["ovn.ingress_mode"]) {
err = SubnetIterate(externalRoute, func(ip net.IP) error {
err = n.ovnnb.CreateLogicalRouterNAT(context.TODO(), n.getRouterName(), "dnat_and_snat", nil, ip, ip, true, true)
if err != nil {
return err
}
reverter.Add(func() {
_ = n.ovnnb.DeleteLogicalRouterNAT(context.TODO(), n.getRouterName(), "dnat_and_snat", false, ip)
})
return nil
})
if err != nil {
return "", nil, err
}
}
}
if len(routes) > 0 {
// Add routes to local router.
err = n.ovnnb.CreateLogicalRouterRoute(context.TODO(), n.getRouterName(), true, routes...)
if err != nil {
return "", nil, err
}
routePrefixes := make([]net.IPNet, 0, len(routes))
for _, route := range routes {
routePrefixes = append(routePrefixes, route.Prefix)
}
reverter.Add(func() {
_ = n.ovnnb.DeleteLogicalRouterRoute(context.TODO(), n.getRouterName(), routePrefixes...)
})
// Add routes to internal switch's address set for ACL usage.
err = n.ovnnb.UpdateAddressSetAdd(context.TODO(), acl.OVNIntSwitchPortGroupAddressSetPrefix(n.ID()), routePrefixes...)
if err != nil {
return "", nil, fmt.Errorf("Failed adding switch address set entries: %w", err)
}
reverter.Add(func() {
_ = n.ovnnb.UpdateAddressSetRemove(context.TODO(), acl.OVNIntSwitchPortGroupAddressSetPrefix(n.ID()), routePrefixes...)
})
routerIntPortIPv4, _, err := n.parseRouterIntPortIPv4Net()
if err != nil {
return "", nil, fmt.Errorf("Failed parsing local router's peering port IPv4 Net: %w", err)
}
routerIntPortIPv6, _, err := n.parseRouterIntPortIPv6Net()
if err != nil {
return "", nil, fmt.Errorf("Failed parsing local router's peering port IPv6 Net: %w", err)
}
// Add routes to peer routers, and security policies for each peer port on local router.
err = n.forPeers(func(targetOVNNet *ovn) error {
targetRouterName := targetOVNNet.getRouterName()
targetRouterPort := targetOVNNet.getLogicalRouterPeerPortName(n.ID())
targetRouterRoutes := make([]networkOVN.OVNRouterRoute, 0, len(routes))
for _, route := range routes {
nexthop := routerIntPortIPv4
if route.Prefix.IP.To4() == nil {
nexthop = routerIntPortIPv6
}
if nexthop == nil {
continue // Skip routes that cannot be supported by local router.
}
targetRouterRoutes = append(targetRouterRoutes, networkOVN.OVNRouterRoute{
Prefix: route.Prefix,
NextHop: nexthop,
Port: targetRouterPort,
})
}
err = n.ovnnb.CreateLogicalRouterRoute(context.TODO(), targetRouterName, true, targetRouterRoutes...)
if err != nil {
return fmt.Errorf("Failed adding static routes to peer network %q in project %q: %w", targetOVNNet.Name(), targetOVNNet.Project(), err)
}
reverter.Add(func() { _ = n.ovnnb.DeleteLogicalRouterRoute(context.TODO(), targetRouterName, routePrefixes...) })
return nil
})
if err != nil {
return "", nil, err
}
}
// Merge network and NIC assigned security ACL lists.
netACLNames := util.SplitNTrimSpace(n.config["security.acls"], ",", -1, true)
nicACLNames := util.SplitNTrimSpace(opts.DeviceConfig["security.acls"], ",", -1, true)
for _, aclName := range netACLNames {
if !slices.Contains(nicACLNames, aclName) {
nicACLNames = append(nicACLNames, aclName)
}
}
// Apply Security ACL port group settings.
addChangeSet := map[networkOVN.OVNPortGroup][]networkOVN.OVNSwitchPortUUID{}
removeChangeSet := map[networkOVN.OVNPortGroup][]networkOVN.OVNSwitchPortUUID{}
// Get logical port UUID.
portUUID, err := n.ovnnb.GetLogicalSwitchPortUUID(context.TODO(), instancePortName)
if err != nil || portUUID == "" {
return "", nil, fmt.Errorf("Failed getting logical port UUID for security ACL removal: %w", err)
}
// Add NIC port to network port group (this includes the port in the @internal subject for ACL rules).
acl.OVNPortGroupInstanceNICSchedule(portUUID, addChangeSet, acl.OVNIntSwitchPortGroupName(n.ID()))
n.logger.Debug("Scheduled logical port for network port group addition", logger.Ctx{"portGroup": acl.OVNIntSwitchPortGroupName(n.ID()), "port": instancePortName})
if len(nicACLNames) > 0 || len(securityACLsRemove) > 0 {
var aclNameIDs map[string]int64
err = n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
// Get map of ACL names to DB IDs (used for generating OVN port group names).
acls, err := dbCluster.GetNetworkACLs(ctx, tx.Tx(), dbCluster.NetworkACLFilter{Project: &n.project})
if err != nil {
return err
}
aclNameIDs = make(map[string]int64, len(acls))
for _, acl := range acls {
aclNameIDs[acl.Name] = int64(acl.ID)
}
return nil
})
if err != nil {
return "", nil, fmt.Errorf("Failed getting network ACL IDs for security ACL setup: %w", err)
}
// Add port to ACLs requested.
if len(nicACLNames) > 0 {
// Request our network is setup with the specified ACLs.
aclNets := map[string]acl.NetworkACLUsage{
n.Name(): {Name: n.Name(), Type: n.Type(), ID: n.ID(), Config: n.Config()},
}
cleanup, err := acl.OVNEnsureACLs(n.state, n.logger, n.ovnnb, n.Project(), aclNameIDs, aclNets, nicACLNames, false)
if err != nil {
return "", nil, fmt.Errorf("Failed ensuring security ACLs are configured in OVN for instance: %w", err)
}
reverter.Add(cleanup)
for _, aclName := range nicACLNames {
aclID, found := aclNameIDs[aclName]
if !found {
return "", nil, fmt.Errorf("Cannot find security ACL ID for %q", aclName)
}
// Add NIC port to ACL port group.
portGroupName := acl.OVNACLPortGroupName(aclID)
acl.OVNPortGroupInstanceNICSchedule(portUUID, addChangeSet, portGroupName)
n.logger.Debug("Scheduled logical port for ACL port group addition", logger.Ctx{"networkACL": aclName, "portGroup": portGroupName, "port": instancePortName})
}
}
// Remove port from ACLs requested.
for _, aclName := range securityACLsRemove {
// Don't remove ACLs that are in the add ACLs list (there are possibly added from
// the network assigned ACLs).
if slices.Contains(nicACLNames, aclName) {
continue
}
aclID, found := aclNameIDs[aclName]
if !found {
return "", nil, fmt.Errorf("Cannot find security ACL ID for %q", aclName)
}
// Remove NIC port from ACL port group.
portGroupName := acl.OVNACLPortGroupName(aclID)
acl.OVNPortGroupInstanceNICSchedule(portUUID, removeChangeSet, portGroupName)
n.logger.Debug("Scheduled logical port for ACL port group removal", logger.Ctx{"networkACL": aclName, "portGroup": portGroupName, "port": instancePortName})
}
}
// Add instance NIC switch port to port groups required. Always run this as the addChangeSet should always
// be populated even if no ACLs being applied, because the NIC port needs to be added to the network level
// port group.
n.logger.Debug("Applying instance NIC port group member change sets")
err = n.ovnnb.UpdatePortGroupMembers(context.TODO(), addChangeSet, removeChangeSet)
if err != nil {
return "", nil, fmt.Errorf("Failed applying OVN port group member change sets for instance NIC: %w", err)
}
// Set the automatic default ACL rule for the port.
if len(nicACLNames) > 0 {
ingressAction, ingressLogged := n.instanceDeviceACLDefaults(opts.DeviceConfig, "ingress")
egressAction, egressLogged := n.instanceDeviceACLDefaults(opts.DeviceConfig, "egress")
logPrefix := fmt.Sprintf("%s-%s", opts.InstanceUUID, opts.DeviceName)
err = acl.OVNApplyInstanceNICDefaultRules(n.ovnnb, acl.OVNIntSwitchPortGroupName(n.ID()), logPrefix, instancePortName, ingressAction, ingressLogged, egressAction, egressLogged)
if err != nil {
return "", nil, fmt.Errorf("Failed applying OVN default ACL rules for instance NIC: %w", err)
}
n.logger.Debug("Set NIC default rule", logger.Ctx{"port": instancePortName, "ingressAction": ingressAction, "ingressLogged": ingressLogged, "egressAction": egressAction, "egressLogged": egressLogged})
} else {
err = n.ovnnb.ClearPortGroupPortACLRules(context.TODO(), acl.OVNIntSwitchPortGroupName(n.ID()), instancePortName)
if err != nil {
return "", nil, fmt.Errorf("Failed clearing OVN default ACL rules for instance NIC: %w", err)
}
n.logger.Debug("Cleared NIC default rule", logger.Ctx{"port": instancePortName})
}
reverter.Success()
return instancePortName, dnsIPs, nil
}
// instanceDeviceACLDefaults returns the action and logging mode to use for the specified direction's default rule.
// If the security.acls.default.{in,e}gress.action or security.acls.default.{in,e}gress.logged settings are not
// specified in the NIC device config, then the settings on the network are used, and if not specified there then
// it returns "reject" and false respectively.
func (n *ovn) instanceDeviceACLDefaults(deviceConfig deviceConfig.Device, direction string) (string, bool) {
defaults := map[string]string{
fmt.Sprintf("security.acls.default.%s.action", direction): "reject",
fmt.Sprintf("security.acls.default.%s.logged", direction): "false",
}
for k := range defaults {
if deviceConfig[k] != "" {
defaults[k] = deviceConfig[k]
} else if n.config[k] != "" {
defaults[k] = n.config[k]
}
}
return defaults[fmt.Sprintf("security.acls.default.%s.action", direction)], util.IsTrue(defaults[fmt.Sprintf("security.acls.default.%s.logged", direction)])
}
// InstanceDevicePortIPs returns the allocated IPs for a device port.
func (n *ovn) InstanceDevicePortIPs(instanceUUID string, deviceName string) ([]net.IP, error) {
if instanceUUID == "" {
return nil, errors.New("Instance UUID is required")
}
instancePortName := n.getInstanceDevicePortName(instanceUUID, deviceName)
devIPs, err := n.ovnnb.GetLogicalSwitchPortIPs(context.TODO(), instancePortName)
if err != nil {
return nil, fmt.Errorf("Failed to get OVN switch port IPs: %w", err)
}
return devIPs, nil
}
// InstanceDevicePortStop deletes an instance device port from the internal logical switch.
func (n *ovn) InstanceDevicePortStop(ovsExternalOVNPort networkOVN.OVNSwitchPort, opts *OVNInstanceNICStopOpts) error {
// Decide whether to use OVS provided OVN port name or internally derived OVN port name.
instancePortName := ovsExternalOVNPort
source := "OVS"
if ovsExternalOVNPort == "" {
if opts.InstanceUUID == "" {
return errors.New("Instance UUID is required")
}
instancePortName = n.getInstanceDevicePortName(opts.InstanceUUID, opts.DeviceName)
source = "internal"
}
portLocation, err := n.ovnnb.GetLogicalSwitchPortLocation(context.TODO(), instancePortName)
if err != nil {
return fmt.Errorf("Failed getting instance switch port options: %w", err)
}
// Don't delete logical switch port if already active on another chassis (i.e during live cluster move).
if portLocation != "" && portLocation != n.state.ServerName {
return nil
}
n.logger.Debug("Deleting instance port", logger.Ctx{"port": instancePortName, "source": source})
internalRoutes, externalRoutes, err := n.instanceDevicePortRoutesParse(opts.DeviceConfig)
if err != nil {
return fmt.Errorf("Failed parsing NIC device routes: %w", err)
}
var uplink *api.Network
err = n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
// Load uplink network config.
_, uplink, _, err = tx.GetNetworkInAnyState(ctx, api.ProjectDefaultName, n.config["network"])
return err
})
if err != nil {
return fmt.Errorf("Failed to load uplink network %q: %w", n.config["network"], err)
}
// Get DNS records.
dnsUUID, _, dnsIPs, err := n.ovnnb.GetLogicalSwitchPortDNS(context.TODO(), instancePortName)
if err != nil {
return err
}
// Cleanup logical switch port and associated config.
err = n.ovnnb.CleanupLogicalSwitchPort(context.TODO(), instancePortName, n.getIntSwitchName(), acl.OVNIntSwitchPortGroupName(n.ID()), dnsUUID)
if err != nil {
return err
}
var removeRoutes []net.IPNet
var removeNATIPs []net.IP
if len(dnsIPs) > 0 {
// When using l3only mode the instance port's IPs are added as static routes to the router.
// So try and remove these in case l3only is (or was) being used.
for _, dnsIP := range dnsIPs {
removeRoutes = append(removeRoutes, IPToNet(dnsIP))
}
// Delete any associated external IP DNAT rules for the DNS IPs.
removeNATIPs = append(removeNATIPs, dnsIPs...)
}
// Delete internal routes.
if len(internalRoutes) > 0 {
for _, internalRoute := range internalRoutes {
removeRoutes = append(removeRoutes, *internalRoute)
}
}
// Delete external routes.
for _, externalRoute := range externalRoutes {
removeRoutes = append(removeRoutes, *externalRoute)
// Remove the DNAT rules when using l2proxy ingress mode on uplink.
if slices.Contains([]string{"l2proxy", ""}, uplink.Config["ovn.ingress_mode"]) {
err = SubnetIterate(externalRoute, func(ip net.IP) error {
removeNATIPs = append(removeNATIPs, ip)
return nil
})
if err != nil {
return err
}
}
}
if len(removeRoutes) > 0 {
// Delete routes from local router.
err = n.ovnnb.DeleteLogicalRouterRoute(context.TODO(), n.getRouterName(), removeRoutes...)
if err != nil {
return err
}
// Delete routes from switch address set.
err = n.ovnnb.UpdateAddressSetRemove(context.TODO(), acl.OVNIntSwitchPortGroupAddressSetPrefix(n.ID()), removeRoutes...)
if err != nil {
return fmt.Errorf("Failed deleting switch address set entries: %w", err)
}
// Delete routes from peer routers.
err = n.forPeers(func(targetOVNNet *ovn) error {
targetRouterName := targetOVNNet.getRouterName()
err = n.ovnnb.DeleteLogicalRouterRoute(context.TODO(), targetRouterName, removeRoutes...)
if err != nil {
return fmt.Errorf("Failed deleting static routes from peer network %q in project %q: %w", targetOVNNet.Name(), targetOVNNet.Project(), err)
}
return nil
})
if err != nil {
return err
}
}
if len(removeNATIPs) > 0 {
err = n.ovnnb.DeleteLogicalRouterNAT(context.TODO(), n.getRouterName(), "dnat_and_snat", false, removeNATIPs...)
if err != nil {
return err
}
}
// Tear down per‑NIC egress SNAT rules (ipv4/ipv6.address.external)
for _, keyPrefix := range []string{"ipv4", "ipv6"} {
// Check if the address is present.
value := opts.DeviceConfig[fmt.Sprintf("%s.address.external", keyPrefix)]
if value == "" {
continue
}
// Validate the address.
extIP := net.ParseIP(value)
if extIP == nil {
return fmt.Errorf("Invalid external address %q", value)
}
// Remove the SNAT entry.
err := n.ovnnb.DeleteLogicalRouterNAT(context.TODO(), n.getRouterName(), "snat", false, extIP)
if err != nil && !errors.Is(err, networkOVN.ErrNotFound) {
return err
}
}
return nil
}
// InstanceDevicePortRemove unregisters the NIC device in the OVN database by removing the DNS entry that should
// have been created during InstanceDevicePortAdd(). If the DNS record exists at remove time then this indicates
// the NIC device was successfully added and this function also clears any DHCP reservations for the NIC's IPs.
func (n *ovn) InstanceDevicePortRemove(instanceUUID string, deviceName string, deviceConfig deviceConfig.Device) error {
instancePortName := n.getInstanceDevicePortName(instanceUUID, deviceName)
reverter := revert.New()
defer reverter.Fail()
// Get DNS records.
dnsUUID, _, _, err := n.ovnnb.GetLogicalSwitchPortDNS(context.TODO(), instancePortName)
if err != nil {
return err
}
// Remove DNS record if exists.
if dnsUUID != "" {
// If NIC has static IPv4 address then remove the DHCPv4 reservation.
if deviceConfig["ipv4.address"] != "" {
ip := net.ParseIP(deviceConfig["ipv4.address"])
if ip != nil {
dhcpReservations, err := n.ovnnb.GetLogicalSwitchDHCPv4Revervations(context.TODO(), n.getIntSwitchName())
if err != nil {
return fmt.Errorf("Failed getting DHCPv4 reservations: %w", err)
}
dhcpReservations = append(dhcpReservations, iprange.Range{Start: ip})
dhcpReservationsNew := make([]iprange.Range, 0, len(dhcpReservations))
found := false
for _, dhcpReservation := range dhcpReservations {
if dhcpReservation.Start.Equal(ip) && dhcpReservation.End == nil {
found = true
continue
}
dhcpReservationsNew = append(dhcpReservationsNew, dhcpReservation)
}
if found {
err = n.ovnnb.UpdateLogicalSwitchDHCPv4Revervations(context.TODO(), n.getIntSwitchName(), dhcpReservationsNew)
if err != nil {
return fmt.Errorf("Failed removing DHCPv4 reservation for %q: %w", ip.String(), err)
}
}
}
}
err = n.ovnnb.DeleteLogicalSwitchPortDNS(context.TODO(), n.getIntSwitchName(), dnsUUID, true)
if err != nil {
return fmt.Errorf("Failed deleting DNS record: %w", err)
}
}
reverter.Success()
return nil
}
// DHCPv4Subnet returns the DHCPv4 subnet (if DHCP is enabled on network).
func (n *ovn) DHCPv4Subnet() *net.IPNet {
// DHCP is disabled on this network (an empty ipv4.dhcp setting indicates enabled by default).
if util.IsFalse(n.config["ipv4.dhcp"]) {
return nil
}
_, subnet, err := n.parseRouterIntPortIPv4Net()
if err != nil {
return nil
}
return subnet
}
// DHCPv6Subnet returns the DHCPv6 subnet (if DHCP or SLAAC is enabled on network).
func (n *ovn) DHCPv6Subnet() *net.IPNet {
// DHCP is disabled on this network (an empty ipv6.dhcp setting indicates enabled by default).
if util.IsFalse(n.config["ipv6.dhcp"]) {
return nil
}
_, subnet, err := n.parseRouterIntPortIPv6Net()
if err != nil {
return nil
}
if subnet != nil {
ones, _ := subnet.Mask.Size()
if ones < 64 {
return nil // OVN only supports DHCPv6 allocated using EUI64 (which needs at least a /64).
}
}
return subnet
}
// ovnNetworkExternalSubnets returns a list of external subnets used by OVN networks using the same uplink as this
// OVN network. OVN networks are considered to be using external subnets for their ipv4.address and/or ipv6.address
// if they have NAT disabled, and/or if they have external NAT addresses specified.
func (n *ovn) ovnNetworkExternalSubnets(ovnProjectNetworksWithOurUplink map[string][]*api.Network) ([]externalSubnetUsage, error) {
externalSubnets := make([]externalSubnetUsage, 0)
for netProject, networks := range ovnProjectNetworksWithOurUplink {
for _, netInfo := range networks {
for _, keyPrefix := range []string{"ipv4", "ipv6"} {
// If NAT is disabled, then network subnet is an external subnet.
if util.IsFalseOrEmpty(netInfo.Config[fmt.Sprintf("%s.nat", keyPrefix)]) {
key := fmt.Sprintf("%s.address", keyPrefix)
_, ipNet, err := net.ParseCIDR(netInfo.Config[key])
if err != nil {
continue // Skip invalid/unspecified network addresses.
}
externalSubnets = append(externalSubnets, externalSubnetUsage{
subnet: *ipNet,
networkProject: netProject,
networkName: netInfo.Name,
usageType: subnetUsageNetwork,
})
}
// Find any external subnets used for network SNAT.
if netInfo.Config[fmt.Sprintf("%s.nat.address", keyPrefix)] != "" {
key := fmt.Sprintf("%s.nat.address", keyPrefix)
subnetSize := 128
if keyPrefix == "ipv4" {
subnetSize = 32
}
_, ipNet, err := net.ParseCIDR(fmt.Sprintf("%s/%d", netInfo.Config[key], subnetSize))
if err != nil {
return nil, fmt.Errorf("Failed parsing %q of %q in project %q: %w", key, netInfo.Name, netProject, err)
}
externalSubnets = append(externalSubnets, externalSubnetUsage{
subnet: *ipNet,
networkProject: netProject,
networkName: netInfo.Name,
usageType: subnetUsageNetworkSNAT,
})
}
}
}
}
return externalSubnets, nil
}
// ovnNICExternalRoutes returns a list of external routes currently used by OVN NICs that are connected to OVN
// networks that share the same uplink as this network uses.
func (n *ovn) ovnNICExternalRoutes(ovnProjectNetworksWithOurUplink map[string][]*api.Network) ([]externalSubnetUsage, error) {
externalRoutes := make([]externalSubnetUsage, 0)
err := n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
return tx.InstanceList(ctx, func(inst db.InstanceArgs, p api.Project) error {
// Get the instance's effective network project name.
instNetworkProject := project.NetworkProjectFromRecord(&p)
devices := db.ExpandInstanceDevices(inst.Devices.Clone(), inst.Profiles)
// Iterate through each of the instance's devices, looking for OVN NICs that are linked to networks
// that use our uplink.
for devName, devConfig := range devices {
if devConfig["type"] != "nic" {
continue
}
// Check whether the NIC device references one of the OVN networks supplied.
if !NICUsesNetwork(devConfig, ovnProjectNetworksWithOurUplink[instNetworkProject]...) {
continue
}
// For OVN NICs that are connected to networks that use the same uplink as we do, check
// if they have any external routes configured, and if so add them to the list to return.
for _, key := range []string{"ipv4.routes.external", "ipv6.routes.external"} {
for _, cidr := range util.SplitNTrimSpace(devConfig[key], ",", -1, true) {
_, ipNet, _ := net.ParseCIDR(cidr)
if ipNet == nil {
// Sip if NIC device doesn't have a valid route.
continue
}
externalRoutes = append(externalRoutes, externalSubnetUsage{
subnet: *ipNet,
networkProject: instNetworkProject,
networkName: devConfig["network"],
instanceProject: inst.Project,
instanceName: inst.Name,
instanceDevice: devName,
usageType: subnetUsageInstance,
})
}
}
}
return nil
})
})
if err != nil {
return nil, err
}
return externalRoutes, nil
}
// ovnProjectNetworksWithUplink accepts a map of all networks in all projects and returns a filtered map of OVN
// networks that use the uplink specified.
func (n *ovn) ovnProjectNetworksWithUplink(uplink string, projectNetworks map[string]map[int64]api.Network) map[string][]*api.Network {
ovnProjectNetworksWithOurUplink := make(map[string][]*api.Network)
for netProject, networks := range projectNetworks {
for _, ni := range networks {
network := ni // Local var creating pointer to rather than iterator.
// Skip non-OVN networks or those networks that don't use the uplink specified.
if network.Type != "ovn" || network.Config["network"] != uplink {
continue
}
if ovnProjectNetworksWithOurUplink[netProject] == nil {
ovnProjectNetworksWithOurUplink[netProject] = []*api.Network{&network}
} else {
ovnProjectNetworksWithOurUplink[netProject] = append(ovnProjectNetworksWithOurUplink[netProject], &network)
}
}
}
return ovnProjectNetworksWithOurUplink
}
// uplinkHasIngressRoutedAnycastIPv4 returns true if the uplink network has IPv4 routed ingress anycast enabled.
func (n *ovn) uplinkHasIngressRoutedAnycastIPv4(uplink *api.Network) bool {
return util.IsTrue(uplink.Config["ipv4.routes.anycast"]) && uplink.Config["ovn.ingress_mode"] == "routed"
}
// uplinkHasIngressRoutedAnycastIPv6 returns true if the uplink network has routed IPv6 ingress anycast enabled.
func (n *ovn) uplinkHasIngressRoutedAnycastIPv6(uplink *api.Network) bool {
return util.IsTrue(uplink.Config["ipv6.routes.anycast"]) && uplink.Config["ovn.ingress_mode"] == "routed"
}
// handleDependencyChange applies changes from uplink network if specific watched keys have changed.
func (n *ovn) handleDependencyChange(uplinkName string, uplinkConfig map[string]string, changedKeys []string) error {
// Detect changes that need to be applied to the network.
for _, k := range []string{"dns.nameservers", "ipv4.gateway", "ipv6.gateway", "ipv4.gateway.hwaddr", "ipv6.gateway.hwaddr"} {
if slices.Contains(changedKeys, k) {
n.logger.Debug("Applying changes from uplink network", logger.Ctx{"uplink": uplinkName})
// Re-setup logical network in order to apply uplink changes.
err := n.setup(true)
if err != nil {
return err
}
break // Only run setup once per notification (all changes will be applied).
}
}
// Add or remove the instance NIC l2proxy DNAT_AND_SNAT rules if uplink's ovn.ingress_mode has changed.
if slices.Contains(changedKeys, "ovn.ingress_mode") {
n.logger.Debug("Applying ingress mode changes from uplink network to instance NICs", logger.Ctx{"uplink": uplinkName})
if slices.Contains([]string{"l2proxy", ""}, uplinkConfig["ovn.ingress_mode"]) {
// Get list of active switch ports (avoids repeated querying of OVN NB).
activePorts, err := n.ovnnb.GetLogicalSwitchPorts(context.TODO(), n.getIntSwitchName())
if err != nil {
return fmt.Errorf("Failed getting active ports: %w", err)
}
// Find all instance NICs that use this network, and re-add the logical OVN instance port.
// This will restore the l2proxy DNAT_AND_SNAT rules.
err = n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
return tx.InstanceList(ctx, func(inst db.InstanceArgs, p api.Project) error {
// Get the instance's effective network project name.
instNetworkProject := project.NetworkProjectFromRecord(&p)
// Skip instances who's effective network project doesn't match this network's
// project.
if n.Project() != instNetworkProject {
return nil
}
devices := db.ExpandInstanceDevices(inst.Devices.Clone(), inst.Profiles)
// Iterate through each of the instance's devices, looking for NICs that are linked
// this network.
for devName, devConfig := range devices {
if devConfig["type"] != "nic" || n.Name() != devConfig["network"] {
continue
}
// Check if instance port exists, if not then we can skip.
instanceUUID := inst.Config["volatile.uuid"]
instancePortName := n.getInstanceDevicePortName(instanceUUID, devName)
_, found := activePorts[instancePortName]
if !found {
continue // No need to update a port that isn't started yet.
}
if devConfig["hwaddr"] == "" {
// Load volatile MAC if no static MAC specified.
devConfig["hwaddr"] = inst.Config[fmt.Sprintf("volatile.%s.hwaddr", devName)]
}
// Re-add logical switch port to apply the l2proxy DNAT_AND_SNAT rules.
n.logger.Debug("Re-adding instance OVN NIC port to apply ingress mode changes", logger.Ctx{"project": inst.Project, "instance": inst.Name, "device": devName})
_, _, err = n.InstanceDevicePortStart(&OVNInstanceNICSetupOpts{
InstanceUUID: instanceUUID,
DNSName: inst.Name,
DeviceName: devName,
DeviceConfig: devConfig,
UplinkConfig: uplinkConfig,
}, nil)
if err != nil {
n.logger.Error("Failed re-adding instance OVN NIC port", logger.Ctx{"project": inst.Project, "instance": inst.Name, "err": err})
continue
}
}
return nil
})
})
if err != nil {
return fmt.Errorf("Failed adding instance NIC ingress mode l2proxy rules: %w", err)
}
} else {
// Remove all DNAT_AND_SNAT rules if not using l2proxy ingress mode, as currently we only
// use DNAT_AND_SNAT rules for this feature so it is safe to do.
err := n.ovnnb.DeleteLogicalRouterNAT(context.TODO(), n.getRouterName(), "dnat_and_snat", true)
if err != nil {
return fmt.Errorf("Failed deleting instance NIC ingress mode l2proxy rules: %w", err)
}
}
}
return nil
}
// forwardFlattenVIPs flattens forwards into format compatible with OVN load balancers.
func (n *ovn) forwardFlattenVIPs(listenAddress net.IP, defaultTargetAddress net.IP, portMaps []*forwardPortMap) []networkOVN.OVNLoadBalancerVIP {
var vips []networkOVN.OVNLoadBalancerVIP
if defaultTargetAddress != nil {
vips = append(vips, networkOVN.OVNLoadBalancerVIP{
ListenAddress: listenAddress,
Targets: []networkOVN.OVNLoadBalancerTarget{{Address: defaultTargetAddress}},
})
}
for _, portMap := range portMaps {
targetPortsLen := len(portMap.target.ports)
for i, lp := range portMap.listenPorts {
targetPort := lp // Default to using same port as listen port for target port.
if targetPortsLen == 1 {
// If a single target port is specified, forward all listen ports to it.
targetPort = portMap.target.ports[0]
} else if targetPortsLen > 1 {
// If more than 1 target port specified, use listen port index to get the
// target port to use.
targetPort = portMap.target.ports[i]
}
vips = append(vips, networkOVN.OVNLoadBalancerVIP{
ListenAddress: listenAddress,
Protocol: portMap.protocol,
ListenPort: lp,
Targets: []networkOVN.OVNLoadBalancerTarget{
{
Address: portMap.target.address,
Port: targetPort,
},
},
})
}
}
return vips
}
// ForwardCreate creates a network forward.
func (n *ovn) ForwardCreate(forward api.NetworkForwardsPost, clientType request.ClientType) error {
if n.config["network"] == "none" {
return errors.New("Isolated OVN network cannot use network forwards")
}
reverter := revert.New()
defer reverter.Fail()
if clientType == request.ClientTypeNormal {
memberSpecific := false // OVN doesn't support per-member forwards.
err := n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
// Check if there is an existing forward using the same listen address.
_, err := dbCluster.GetNetworkForward(ctx, tx.Tx(), n.ID(), forward.ListenAddress)
return err
})
if err == nil {
return api.StatusErrorf(http.StatusConflict, "A forward for that listen address already exists")
}
// Convert listen address to subnet so we can check its valid and can be used.
listenAddressNet, err := ParseIPToNet(forward.ListenAddress)
if err != nil {
return fmt.Errorf("Failed parsing %q: %w", forward.ListenAddress, err)
}
portMaps, err := n.forwardValidate(listenAddressNet.IP, &forward.NetworkForwardPut)
if err != nil {
return err
}
// Load the project to get uplink network restrictions.
var p *api.Project
var uplink *api.Network
err = n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
project, err := dbCluster.GetProject(ctx, tx.Tx(), n.project)
if err != nil {
return fmt.Errorf("Failed to load network restrictions from project %q: %w", n.project, err)
}
p, err = project.ToAPI(ctx, tx.Tx())
if err != nil {
return fmt.Errorf("Failed to load network restrictions from project %q: %w", n.project, err)
}
// Get uplink routes.
_, uplink, _, err = tx.GetNetworkInAnyState(ctx, api.ProjectDefaultName, n.config["network"])
if err != nil {
return fmt.Errorf("Failed to load uplink network %q: %w", n.config["network"], err)
}
return nil
})
if err != nil {
return err
}
// Get project restricted routes.
projectRestrictedSubnets, err := n.projectRestrictedSubnets(p, n.config["network"])
if err != nil {
return err
}
externalSubnetsInUse, err := n.getExternalSubnetInUse(n.config["network"])
if err != nil {
return err
}
// Check the listen address subnet is allowed within both the uplink's external routes and any
// project restricted subnets.
err = n.validateExternalSubnet(uplink, projectRestrictedSubnets, listenAddressNet)
if err != nil {
return err
}
// Check the listen address subnet doesn't fall within any existing OVN network external subnets.
for _, externalSubnetUser := range externalSubnetsInUse {
// Check if usage is from our own network.
if externalSubnetUser.networkProject == n.project && externalSubnetUser.networkName == n.name {
// Skip checking conflict with our own network's subnet or SNAT address.
// But do not allow other conflict with other usage types within our own network.
if externalSubnetUser.usageType == subnetUsageNetwork || externalSubnetUser.usageType == subnetUsageNetworkSNAT {
continue
}
}
if SubnetContains(&externalSubnetUser.subnet, listenAddressNet) || SubnetContains(listenAddressNet, &externalSubnetUser.subnet) {
// This error is purposefully vague so that it doesn't reveal any names of
// resources potentially outside of the network's project.
return fmt.Errorf("Forward listen address %q overlaps with another network or NIC", listenAddressNet.String())
}
}
var forwardID int64
err = n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
// Create forward DB record.
nodeID := sql.NullInt64{
Valid: memberSpecific,
Int64: tx.GetNodeID(),
}
dbRecord := dbCluster.NetworkForward{
NetworkID: n.ID(),
NodeID: nodeID,
ListenAddress: forward.ListenAddress,
Description: forward.Description,
Ports: forward.Ports,
}
if forward.Ports == nil {
dbRecord.Ports = []api.NetworkForwardPort{}
}
forwardID, err = dbCluster.CreateNetworkForward(ctx, tx.Tx(), dbRecord)
if err != nil {
return err
}
err = dbCluster.CreateNetworkForwardConfig(ctx, tx.Tx(), forwardID, forward.Config)
if err != nil {
return err
}
return nil
})
if err != nil {
return err
}
reverter.Add(func() {
_ = n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
return dbCluster.DeleteNetworkForward(ctx, tx.Tx(), n.ID(), forwardID)
})
_ = n.ovnnb.DeleteLoadBalancer(context.TODO(), n.getLoadBalancerName(forward.ListenAddress))
_ = n.forwardBGPSetupPrefixes()
})
vips := n.forwardFlattenVIPs(net.ParseIP(forward.ListenAddress), net.ParseIP(forward.Config["target_address"]), portMaps)
err = n.ovnnb.CreateLoadBalancer(context.TODO(), n.getLoadBalancerName(forward.ListenAddress), n.getRouterName(), n.getIntSwitchName(), vips...)
if err != nil {
return fmt.Errorf("Failed applying OVN load balancer: %w", err)
}
// Notify all other members to refresh their BGP prefixes.
notifier, err := cluster.NewNotifier(n.state, n.state.Endpoints.NetworkCert(), n.state.ServerCert(), cluster.NotifyAll)
if err != nil {
return err
}
err = notifier(func(client incus.InstanceServer) error {
return client.UseProject(n.project).CreateNetworkForward(n.name, forward)
})
if err != nil {
return err
}
}
// Refresh exported BGP prefixes on local member.
err := n.forwardBGPSetupPrefixes()
if err != nil {
return fmt.Errorf("Failed applying BGP prefixes for address forwards: %w", err)
}
reverter.Success()
return nil
}
// ForwardUpdate updates a network forward.
func (n *ovn) ForwardUpdate(listenAddress string, req api.NetworkForwardPut, clientType request.ClientType) error {
reverter := revert.New()
defer reverter.Fail()
if clientType == request.ClientTypeNormal {
var curForwardID int64
var curForward *api.NetworkForward
err := n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
var err error
// No memberSpecific filtering needed because OVN doesn't support per-member-forwards
dbRecord, err := dbCluster.GetNetworkForward(ctx, tx.Tx(), n.ID(), listenAddress)
if err != nil {
return err
}
curForwardID = dbRecord.ID
curForward, err = dbRecord.ToAPI(ctx, tx.Tx())
if err != nil {
return err
}
return nil
})
if err != nil {
return err
}
portMaps, err := n.forwardValidate(net.ParseIP(curForward.ListenAddress), &req)
if err != nil {
return err
}
curForwardEtagHash, err := localUtil.EtagHash(curForward.Etag())
if err != nil {
return err
}
newForward := api.NetworkForward{
ListenAddress: curForward.ListenAddress,
NetworkForwardPut: req,
}
newForwardEtagHash, err := localUtil.EtagHash(newForward.Etag())
if err != nil {
return err
}
if curForwardEtagHash == newForwardEtagHash {
return nil // Nothing has changed.
}
vips := n.forwardFlattenVIPs(net.ParseIP(newForward.ListenAddress), net.ParseIP(newForward.Config["target_address"]), portMaps)
err = n.ovnnb.CreateLoadBalancer(context.TODO(), n.getLoadBalancerName(newForward.ListenAddress), n.getRouterName(), n.getIntSwitchName(), vips...)
if err != nil {
return fmt.Errorf("Failed applying OVN load balancer: %w", err)
}
reverter.Add(func() {
// Apply old settings to OVN on failure.
portMaps, err := n.forwardValidate(net.ParseIP(curForward.ListenAddress), &curForward.NetworkForwardPut)
if err == nil {
vips := n.forwardFlattenVIPs(net.ParseIP(curForward.ListenAddress), net.ParseIP(curForward.Config["target_address"]), portMaps)
_ = n.ovnnb.CreateLoadBalancer(context.TODO(), n.getLoadBalancerName(curForward.ListenAddress), n.getRouterName(), n.getIntSwitchName(), vips...)
_ = n.forwardBGPSetupPrefixes()
}
})
err = n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
fwd := dbCluster.NetworkForward{
NetworkID: n.ID(),
ListenAddress: listenAddress,
Description: newForward.Description,
Ports: newForward.Ports,
}
err = dbCluster.UpdateNetworkForward(ctx, tx.Tx(), n.ID(), listenAddress, fwd)
if err != nil {
return err
}
err = dbCluster.UpdateNetworkForwardConfig(ctx, tx.Tx(), curForwardID, newForward.Config)
if err != nil {
return err
}
return nil
})
if err != nil {
return err
}
reverter.Add(func() {
_ = n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
fwd := dbCluster.NetworkForward{
NetworkID: n.ID(),
ListenAddress: listenAddress,
Description: curForward.Description,
Ports: curForward.Ports,
}
err = dbCluster.UpdateNetworkForward(ctx, tx.Tx(), n.ID(), listenAddress, fwd)
if err != nil {
return err
}
err = dbCluster.UpdateNetworkForwardConfig(ctx, tx.Tx(), curForwardID, curForward.Config)
if err != nil {
return err
}
return nil
})
})
// Notify all other members to refresh their BGP prefixes.
notifier, err := cluster.NewNotifier(n.state, n.state.Endpoints.NetworkCert(), n.state.ServerCert(), cluster.NotifyAll)
if err != nil {
return err
}
err = notifier(func(client incus.InstanceServer) error {
return client.UseProject(n.project).UpdateNetworkForward(n.name, curForward.ListenAddress, req, "")
})
if err != nil {
return err
}
}
// Refresh exported BGP prefixes on local member.
err := n.forwardBGPSetupPrefixes()
if err != nil {
return fmt.Errorf("Failed applying BGP prefixes for address forwards: %w", err)
}
reverter.Success()
return nil
}
// ForwardDelete deletes a network forward.
func (n *ovn) ForwardDelete(listenAddress string, clientType request.ClientType) error {
if clientType == request.ClientTypeNormal {
var forwardID int64
var forward *api.NetworkForward
err := n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
var err error
// No memberSpecific filtering needed because OVN doesn't support per-member-forwards
dbRecord, err := dbCluster.GetNetworkForward(ctx, tx.Tx(), n.ID(), listenAddress)
if err != nil {
return err
}
forwardID = dbRecord.ID
forward, err = dbRecord.ToAPI(ctx, tx.Tx())
if err != nil {
return err
}
return nil
})
if err != nil {
return err
}
// Delete the network forward itself.
err = n.ovnnb.DeleteLoadBalancer(context.TODO(), n.getLoadBalancerName(forward.ListenAddress))
if err != nil {
return fmt.Errorf("Failed deleting OVN load balancer: %w", err)
}
// Delete static route to network forward if present.
vip, err := ParseIPToNet(forward.ListenAddress)
if err != nil {
return err
}
_ = n.ovnnb.DeleteLogicalRouterRoute(context.TODO(), n.getRouterName(), *vip)
// Delete the database records.
err = n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
return dbCluster.DeleteNetworkForward(ctx, tx.Tx(), n.ID(), forwardID)
})
if err != nil {
return err
}
// Notify all other members to refresh their BGP prefixes.
notifier, err := cluster.NewNotifier(n.state, n.state.Endpoints.NetworkCert(), n.state.ServerCert(), cluster.NotifyAll)
if err != nil {
return err
}
err = notifier(func(client incus.InstanceServer) error {
return client.UseProject(n.project).DeleteNetworkForward(n.name, forward.ListenAddress)
})
if err != nil {
return err
}
}
// Refresh exported BGP prefixes on local member.
err := n.forwardBGPSetupPrefixes()
if err != nil {
return fmt.Errorf("Failed applying BGP prefixes for address forwards: %w", err)
}
return nil
}
// loadBalancerFlattenVIPs flattens port maps into format compatible with OVN load balancers.
func (n *ovn) loadBalancerFlattenVIPs(listenAddress net.IP, portMaps []*loadBalancerPortMap) []networkOVN.OVNLoadBalancerVIP {
var vips []networkOVN.OVNLoadBalancerVIP
for _, portMap := range portMaps {
for i, lp := range portMap.listenPorts {
vip := networkOVN.OVNLoadBalancerVIP{
ListenAddress: listenAddress,
Protocol: portMap.protocol,
ListenPort: lp,
}
for _, target := range portMap.targets {
targetPort := lp // Default to using same port as listen port for target port.
targetPortsLen := len(target.ports)
if targetPortsLen == 1 {
// If a single target port is specified, forward all listen ports to it.
targetPort = target.ports[0]
} else if targetPortsLen > 1 {
// If more than 1 target port specified, use listen port index to get the
// target port to use.
targetPort = target.ports[i]
}
vip.Targets = append(vip.Targets, networkOVN.OVNLoadBalancerTarget{
Address: target.address,
Port: targetPort,
})
}
vips = append(vips, vip)
}
}
return vips
}
// LoadBalancerCreate creates a network load balancer.
func (n *ovn) LoadBalancerCreate(loadBalancer api.NetworkLoadBalancersPost, clientType request.ClientType) error {
if n.config["network"] == "none" {
return errors.New("Isolated OVN network cannot use network load balancers")
}
reverter := revert.New()
defer reverter.Fail()
if clientType == request.ClientTypeNormal {
err := n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
// Check if there is an existing load balancer using the same listen address.
_, err := dbCluster.GetNetworkLoadBalancer(ctx, tx.Tx(), n.ID(), loadBalancer.ListenAddress)
if err != nil {
return err
}
return nil
})
if err == nil {
return api.StatusErrorf(http.StatusConflict, "A load balancer for that listen address already exists")
}
// Convert listen address to subnet so we can check its valid and can be used.
listenAddressNet, err := ParseIPToNet(loadBalancer.ListenAddress)
if err != nil {
return fmt.Errorf("Failed parsing %q: %w", loadBalancer.ListenAddress, err)
}
portMaps, err := n.loadBalancerValidate(listenAddressNet.IP, &loadBalancer.NetworkLoadBalancerPut)
if err != nil {
return err
}
// Load the project to get uplink network restrictions.
var p *api.Project
var uplink *api.Network
err = n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
project, err := dbCluster.GetProject(ctx, tx.Tx(), n.project)
if err != nil {
return fmt.Errorf("Failed to load network restrictions from project %q: %w", n.project, err)
}
p, err = project.ToAPI(ctx, tx.Tx())
if err != nil {
return fmt.Errorf("Failed to load network restrictions from project %q: %w", n.project, err)
}
// Get uplink routes.
_, uplink, _, err = tx.GetNetworkInAnyState(ctx, api.ProjectDefaultName, n.config["network"])
if err != nil {
return fmt.Errorf("Failed to load uplink network %q: %w", n.config["network"], err)
}
return nil
})
if err != nil {
return err
}
// Get project restricted routes.
projectRestrictedSubnets, err := n.projectRestrictedSubnets(p, n.config["network"])
if err != nil {
return err
}
externalSubnetsInUse, err := n.getExternalSubnetInUse(n.config["network"])
if err != nil {
return err
}
// Check the listen address subnet is allowed within both the uplink's external routes and any
// project restricted subnets.
err = n.validateExternalSubnet(uplink, projectRestrictedSubnets, listenAddressNet)
if err != nil {
return err
}
// Check the listen address subnet doesn't fall within any existing OVN network external subnets.
for _, externalSubnetUser := range externalSubnetsInUse {
// Check if usage is from our own network.
if externalSubnetUser.networkProject == n.project && externalSubnetUser.networkName == n.name {
// Skip checking conflict with our own network's subnet or SNAT address.
// But do not allow other conflict with other usage types within our own network.
if externalSubnetUser.usageType == subnetUsageNetwork || externalSubnetUser.usageType == subnetUsageNetworkSNAT {
continue
}
}
if SubnetContains(&externalSubnetUser.subnet, listenAddressNet) || SubnetContains(listenAddressNet, &externalSubnetUser.subnet) {
// This error is purposefully vague so that it doesn't reveal any names of
// resources potentially outside of the network's project.
return fmt.Errorf("Load balancer listen address %q overlaps with another network or NIC", listenAddressNet.String())
}
}
var loadBalancerID int64
err = n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
// Create load balancer DB record.
lb := dbCluster.NetworkLoadBalancer{
NetworkID: n.ID(),
ListenAddress: loadBalancer.ListenAddress,
Description: loadBalancer.Description,
Backends: loadBalancer.Backends,
Ports: loadBalancer.Ports,
}
loadBalancerID, err = dbCluster.CreateNetworkLoadBalancer(ctx, tx.Tx(), lb)
if err != nil {
return err
}
// Save the load balancer configuration.
err = dbCluster.CreateNetworkLoadBalancerConfig(ctx, tx.Tx(), loadBalancerID, loadBalancer.Config)
if err != nil {
return err
}
return nil
})
if err != nil {
return err
}
reverter.Add(func() {
_ = n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
return dbCluster.DeleteNetworkLoadBalancer(ctx, tx.Tx(), n.ID(), loadBalancerID)
})
_ = n.ovnnb.DeleteLoadBalancer(context.TODO(), n.getLoadBalancerName(loadBalancer.ListenAddress))
_ = n.loadBalancerBGPSetupPrefixes()
})
vips := n.loadBalancerFlattenVIPs(net.ParseIP(loadBalancer.ListenAddress), portMaps)
// Look at health checking configuration.
healthCheck, err := n.getHealthCheck(loadBalancer.NetworkLoadBalancerPut)
if err != nil {
return err
}
if healthCheck != nil {
for i := range vips {
vips[i].HealthCheck = healthCheck
}
}
err = n.ovnnb.CreateLoadBalancer(context.TODO(), n.getLoadBalancerName(loadBalancer.ListenAddress), n.getRouterName(), n.getIntSwitchName(), vips...)
if err != nil {
return fmt.Errorf("Failed applying OVN load balancer: %w", err)
}
// Notify all other members to refresh their BGP prefixes.
notifier, err := cluster.NewNotifier(n.state, n.state.Endpoints.NetworkCert(), n.state.ServerCert(), cluster.NotifyAll)
if err != nil {
return err
}
err = notifier(func(client incus.InstanceServer) error {
return client.UseProject(n.project).CreateNetworkLoadBalancer(n.name, loadBalancer)
})
if err != nil {
return err
}
}
// Refresh exported BGP prefixes on local member.
err := n.loadBalancerBGPSetupPrefixes()
if err != nil {
return fmt.Errorf("Failed applying BGP prefixes for load balancers: %w", err)
}
reverter.Success()
return nil
}
// LoadBalancerUpdate updates a network load balancer.
func (n *ovn) LoadBalancerUpdate(listenAddress string, req api.NetworkLoadBalancerPut, clientType request.ClientType) error {
reverter := revert.New()
defer reverter.Fail()
if clientType == request.ClientTypeNormal {
var curLoadBalancer *api.NetworkLoadBalancer
var curLoadBalancerID int64
err := n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
networkID := n.ID()
// Get the load balancer.
dbLoadBalancers, err := dbCluster.GetNetworkLoadBalancers(ctx, tx.Tx(), dbCluster.NetworkLoadBalancerFilter{
NetworkID: &networkID,
ListenAddress: &listenAddress,
})
if err != nil {
return err
}
if len(dbLoadBalancers) != 1 {
return api.StatusErrorf(http.StatusNotFound, "Network load balancer not found")
}
// Get the API struct.
curLoadBalancer, err = dbLoadBalancers[0].ToAPI(ctx, tx.Tx())
if err != nil {
return err
}
curLoadBalancerID = dbLoadBalancers[0].ID
return nil
})
if err != nil {
return err
}
portMaps, err := n.loadBalancerValidate(net.ParseIP(curLoadBalancer.ListenAddress), &req)
if err != nil {
return err
}
curEtagHash, err := localUtil.EtagHash(curLoadBalancer.Etag())
if err != nil {
return err
}
newLoadBalancer := api.NetworkLoadBalancer{
ListenAddress: curLoadBalancer.ListenAddress,
NetworkLoadBalancerPut: req,
}
newLoadBalancerEtagHash, err := localUtil.EtagHash(newLoadBalancer.Etag())
if err != nil {
return err
}
if curEtagHash == newLoadBalancerEtagHash {
return nil // Nothing has changed.
}
vips := n.loadBalancerFlattenVIPs(net.ParseIP(newLoadBalancer.ListenAddress), portMaps)
// Look at health checking configuration.
healthCheck, err := n.getHealthCheck(newLoadBalancer.NetworkLoadBalancerPut)
if err != nil {
return err
}
if healthCheck != nil {
for i := range vips {
vips[i].HealthCheck = healthCheck
}
}
err = n.ovnnb.CreateLoadBalancer(context.TODO(), n.getLoadBalancerName(newLoadBalancer.ListenAddress), n.getRouterName(), n.getIntSwitchName(), vips...)
if err != nil {
return fmt.Errorf("Failed applying OVN load balancer: %w", err)
}
reverter.Add(func() {
// Apply old settings to OVN on failure.
portMaps, err := n.loadBalancerValidate(net.ParseIP(curLoadBalancer.ListenAddress), &curLoadBalancer.NetworkLoadBalancerPut)
if err == nil {
vips := n.loadBalancerFlattenVIPs(net.ParseIP(curLoadBalancer.ListenAddress), portMaps)
_ = n.ovnnb.CreateLoadBalancer(context.TODO(), n.getLoadBalancerName(curLoadBalancer.ListenAddress), n.getRouterName(), n.getIntSwitchName(), vips...)
_ = n.forwardBGPSetupPrefixes()
}
})
err = n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
lb := dbCluster.NetworkLoadBalancer{
NetworkID: n.ID(),
ListenAddress: listenAddress,
Description: newLoadBalancer.Description,
Backends: newLoadBalancer.Backends,
Ports: newLoadBalancer.Ports,
}
err = dbCluster.UpdateNetworkLoadBalancer(ctx, tx.Tx(), n.ID(), listenAddress, lb)
if err != nil {
return err
}
err = dbCluster.UpdateNetworkLoadBalancerConfig(ctx, tx.Tx(), curLoadBalancerID, newLoadBalancer.Config)
if err != nil {
return err
}
return nil
})
if err != nil {
return err
}
reverter.Add(func() {
_ = n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
lb := dbCluster.NetworkLoadBalancer{
NetworkID: n.ID(),
ListenAddress: listenAddress,
Description: curLoadBalancer.Description,
Backends: curLoadBalancer.Backends,
Ports: curLoadBalancer.Ports,
}
err = dbCluster.UpdateNetworkLoadBalancer(ctx, tx.Tx(), n.ID(), listenAddress, lb)
if err != nil {
return err
}
err = dbCluster.UpdateNetworkLoadBalancerConfig(ctx, tx.Tx(), curLoadBalancerID, curLoadBalancer.Config)
if err != nil {
return err
}
return nil
})
})
// Notify all other members to refresh their BGP prefixes.
notifier, err := cluster.NewNotifier(n.state, n.state.Endpoints.NetworkCert(), n.state.ServerCert(), cluster.NotifyAll)
if err != nil {
return err
}
err = notifier(func(client incus.InstanceServer) error {
return client.UseProject(n.project).UpdateNetworkLoadBalancer(n.name, curLoadBalancer.ListenAddress, req, "")
})
if err != nil {
return err
}
}
// Refresh exported BGP prefixes on local member.
err := n.loadBalancerBGPSetupPrefixes()
if err != nil {
return fmt.Errorf("Failed applying BGP prefixes for load balancers: %w", err)
}
reverter.Success()
return nil
}
// LoadBalancerState returns the current state of the load balancer.
func (n *ovn) LoadBalancerState(lb api.NetworkLoadBalancer) (*api.NetworkLoadBalancerState, error) {
lbState := &api.NetworkLoadBalancerState{}
if util.IsTrue(lb.Config["healthcheck"]) {
lbState.BackendHealth = map[string]api.NetworkLoadBalancerStateBackendHealth{}
for _, backend := range lb.Backends {
backendHealth := api.NetworkLoadBalancerStateBackendHealth{}
backendHealth.Address = backend.TargetAddress
backendHealth.Ports = []api.NetworkLoadBalancerStateBackendHealthPort{}
for _, lbPort := range lb.Ports {
if !slices.Contains(lbPort.TargetBackend, backend.Name) {
continue
}
// Check valid listen port(s) supplied.
listenPortRanges := util.SplitNTrimSpace(lbPort.ListenPort, ",", -1, true)
if len(listenPortRanges) <= 0 {
return nil, fmt.Errorf("Missing listen port in port specification %q", lbPort.ListenPort)
}
for _, pr := range listenPortRanges {
portFirst, portRange, err := ParsePortRange(pr)
if err != nil {
return nil, fmt.Errorf("Invalid listen port in port specification %q: %w", lbPort.ListenPort, err)
}
for i := range portRange {
port := portFirst + i
status, err := n.ovnsb.GetServiceHealth(context.TODO(), backend.TargetAddress, lbPort.Protocol, int(port))
if err != nil {
return nil, fmt.Errorf("Failed retrieving OVN load-balancer health: %w", err)
}
portHealth := api.NetworkLoadBalancerStateBackendHealthPort{
Protocol: lbPort.Protocol,
Port: int(port),
Status: status,
}
backendHealth.Ports = append(backendHealth.Ports, portHealth)
}
}
}
lbState.BackendHealth[backend.Name] = backendHealth
}
}
return lbState, nil
}
// LoadBalancerDelete deletes a network load balancer.
func (n *ovn) LoadBalancerDelete(listenAddress string, clientType request.ClientType) error {
if clientType == request.ClientTypeNormal {
var lb *dbCluster.NetworkLoadBalancer
err := n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
networkID := n.ID()
dbLoadBalancers, err := dbCluster.GetNetworkLoadBalancers(ctx, tx.Tx(), dbCluster.NetworkLoadBalancerFilter{
NetworkID: &networkID,
ListenAddress: &listenAddress,
})
if err != nil {
return err
}
if len(dbLoadBalancers) != 1 {
return api.StatusErrorf(http.StatusNotFound, "Network load balancer not found")
}
lb = &dbLoadBalancers[0]
return nil
})
if err != nil {
return err
}
// Delete the load balancer itself.
err = n.ovnnb.DeleteLoadBalancer(context.TODO(), n.getLoadBalancerName(lb.ListenAddress))
if err != nil {
return fmt.Errorf("Failed deleting OVN load balancer: %w", err)
}
// Delete static route to load-balancer if present.
vip, err := ParseIPToNet(lb.ListenAddress)
if err != nil {
return err
}
_ = n.ovnnb.DeleteLogicalRouterRoute(context.TODO(), n.getRouterName(), *vip)
// Delete the database records.
err = n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
return dbCluster.DeleteNetworkLoadBalancer(ctx, tx.Tx(), n.ID(), lb.ID)
})
if err != nil {
return err
}
// Notify all other members to refresh their BGP prefixes.
notifier, err := cluster.NewNotifier(n.state, n.state.Endpoints.NetworkCert(), n.state.ServerCert(), cluster.NotifyAll)
if err != nil {
return err
}
err = notifier(func(client incus.InstanceServer) error {
return client.UseProject(n.project).DeleteNetworkLoadBalancer(n.name, lb.ListenAddress)
})
if err != nil {
return err
}
}
// Refresh exported BGP prefixes on local member.
err := n.loadBalancerBGPSetupPrefixes()
if err != nil {
return fmt.Errorf("Failed applying BGP prefixes for address forwards: %w", err)
}
return nil
}
func (n *ovn) getHealthCheck(loadBalancer api.NetworkLoadBalancerPut) (*networkOVN.OVNLoadBalancerHealthCheck, error) {
// Check if load-balancer is enabled.
if !util.IsTrue(loadBalancer.Config["healthcheck"]) {
return nil, nil
}
// Get IPv4 checker.
var checkerIPV4 net.IP
_, ipv4Net, err := n.parseRouterIntPortIPv4Net()
if err == nil && ipv4Net != nil {
checkerIPV4 = dhcpalloc.GetIP(ipv4Net, -2)
}
// Get IPv6 checker.
var checkerIPV6 net.IP
_, ipv6Net, err := n.parseRouterIntPortIPv6Net()
if err == nil && ipv6Net != nil {
checkerIPV6 = dhcpalloc.GetIP(ipv6Net, -2)
}
// Parse the healthcheck options.
hcInterval, err := strconv.Atoi(loadBalancer.Config["healthcheck.interval"])
if err != nil && loadBalancer.Config["healthcheck.interval"] != "" {
return nil, err
}
hcTimeout, err := strconv.Atoi(loadBalancer.Config["healthcheck.timeout"])
if err != nil && loadBalancer.Config["healthcheck.timeout"] != "" {
return nil, err
}
hcFailureCount, err := strconv.Atoi(loadBalancer.Config["healthcheck.failure_count"])
if err != nil && loadBalancer.Config["healthcheck.failure_count"] != "" {
return nil, err
}
hcSuccessCount, err := strconv.Atoi(loadBalancer.Config["healthcheck.success_count"])
if err != nil && loadBalancer.Config["healthcheck.success_count"] != "" {
return nil, err
}
// Prepare the load-balancer health check.
healthCheck := &networkOVN.OVNLoadBalancerHealthCheck{
CheckerIPV4: checkerIPV4,
CheckerIPV6: checkerIPV6,
Interval: hcInterval,
Timeout: hcTimeout,
FailureCount: hcFailureCount,
SuccessCount: hcSuccessCount,
}
return healthCheck, nil
}
// Leases returns a list of leases for the OVN network. Those are directly extracted from the OVN database.
func (n *ovn) Leases(projectName string, clientType request.ClientType) ([]api.NetworkLease, error) {
var err error
leases := []api.NetworkLease{}
// If requested project matches network's project then include gateway IPs.
if projectName == n.project {
// Add our own gateway IPs.
for _, addr := range []string{n.config["ipv4.address"], n.config["ipv6.address"]} {
ip, _, _ := net.ParseCIDR(addr)
if ip != nil {
leases = append(leases, api.NetworkLease{
Hostname: fmt.Sprintf("%s.gw", n.Name()),
Address: ip.String(),
Type: "gateway",
})
}
}
}
// Get all the instances in the requested project that are connected to this network.
filter := dbCluster.InstanceFilter{Project: &projectName}
err = UsedByInstanceDevices(n.state, n.Project(), n.Name(), n.Type(), func(inst db.InstanceArgs, nicName string, nicConfig map[string]string) error {
// Get the instance UUID needed for OVN port name generation.
instanceUUID := inst.Config["volatile.uuid"]
if instanceUUID == "" {
return nil
}
devIPs, err := n.InstanceDevicePortIPs(instanceUUID, nicName)
if err != nil {
return nil // There is likely no active port and so no leases.
}
// Fill in the hwaddr from volatile.
if nicConfig["hwaddr"] == "" {
nicConfig["hwaddr"] = inst.Config[fmt.Sprintf("volatile.%s.hwaddr", nicName)]
}
// Parse the MAC.
hwAddr, _ := net.ParseMAC(nicConfig["hwaddr"])
// Add the leases.
for _, ip := range devIPs {
leaseType := "dynamic"
if nicConfig["ipv4.address"] == ip.String() || nicConfig["ipv6.address"] == ip.String() {
leaseType = "static"
}
leases = append(leases, api.NetworkLease{
Hostname: inst.Name,
Address: ip.String(),
Hwaddr: hwAddr.String(),
Type: leaseType,
Location: inst.Node,
})
}
return nil
}, filter)
if err != nil {
return nil, err
}
return leases, nil
}
// localPeerCreate creates a network peering with another local network.
func (n *ovn) localPeerCreate(peer api.NetworkPeersPost) error {
ctx := context.TODO()
reverter := revert.New()
defer reverter.Fail()
// Get the peer DB record.
var peerInfo *api.NetworkPeer
err := n.state.DB.Cluster.Transaction(ctx, func(ctx context.Context, tx *db.ClusterTx) error {
var err error
// Load peering to get mutual peering info.
dbPeer, err := dbCluster.GetNetworkPeer(ctx, tx.Tx(), n.id, peer.Name)
if err != nil {
return fmt.Errorf("Failed getting network peer DB object: %w", err)
}
var apiErr error
peerInfo, apiErr = dbPeer.ToAPI(ctx, tx.Tx())
if apiErr != nil {
return fmt.Errorf("Failed converting network peer DB object to API object: %w", apiErr)
}
return nil
})
if err != nil {
return err
}
// Validate the peer.
if peerInfo.Status != api.NetworkStatusCreated {
return fmt.Errorf("Only peerings in %q state can be setup", api.NetworkStatusCreated)
}
// Apply router security policies.
// Should have been done during network setup, but ensure its done here anyway.
err = n.logicalRouterPolicySetup(n.ovnnb)
if err != nil {
return fmt.Errorf("Failed applying local router security policy: %w", err)
}
activeLocalNICPorts, err := n.ovnnb.GetLogicalSwitchPorts(context.TODO(), n.getIntSwitchName())
if err != nil {
return fmt.Errorf("Failed getting active NIC ports: %w", err)
}
var localNICRoutes []net.IPNet
// Get routes on instance NICs connected to local network to be added as routes to target network.
err = UsedByInstanceDevices(n.state, n.Project(), n.Name(), n.Type(), func(inst db.InstanceArgs, nicName string, nicConfig map[string]string) error {
instancePortName := n.getInstanceDevicePortName(inst.Config["volatile.uuid"], nicName)
_, found := activeLocalNICPorts[instancePortName]
if !found {
return nil // Don't add config for instance NICs that aren't started.
}
localNICRoutes = append(localNICRoutes, n.instanceNICGetRoutes(nicConfig)...)
return nil
})
if err != nil {
return fmt.Errorf("Failed getting instance NIC routes on local network: %w", err)
}
targetNet, err := LoadByName(n.state, peer.TargetProject, peer.TargetNetwork)
if err != nil {
return fmt.Errorf("Failed loading target network: %w", err)
}
targetOVNNet, ok := targetNet.(*ovn)
if !ok {
return errors.New("Target network is not ovn interface type")
}
opts, err := n.peerGetLocalOpts(localNICRoutes)
if err != nil {
return err
}
// Ensure local subnets and all active NIC routes are present in internal switch's address set.
err = n.ovnnb.UpdateAddressSetAdd(context.TODO(), acl.OVNIntSwitchPortGroupAddressSetPrefix(n.ID()), opts.TargetRouterRoutes...)
if err != nil {
return fmt.Errorf("Failed adding active NIC routes to switch address set: %w", err)
}
err = n.peerSetup(n.ovnnb, targetOVNNet, *opts)
if err != nil {
return err
}
reverter.Success()
return nil
}
// remotePeerCreate creates a network peering with an OVN-IC.
func (n *ovn) remotePeerCreate(peer api.NetworkPeersPost) error {
ctx := context.TODO()
reverter := revert.New()
defer reverter.Fail()
// Load the project.
var p *api.Project
err := n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
project, err := dbCluster.GetProject(ctx, tx.Tx(), n.project)
if err != nil {
return err
}
p, err = project.ToAPI(ctx, tx.Tx())
return err
})
if err != nil {
return fmt.Errorf("Failed to load network restrictions from project %q: %w", n.project, err)
}
// Validate restrictions.
if !project.NetworkIntegrationAllowed(p.Config, peer.TargetIntegration) {
return api.StatusErrorf(http.StatusForbidden, "Project isn't allowed to use this network integration")
}
// Load the integration.
var integration *api.NetworkIntegration
err = n.state.DB.Cluster.Transaction(ctx, func(ctx context.Context, tx *db.ClusterTx) error {
entry, err := dbCluster.GetNetworkIntegration(ctx, tx.Tx(), peer.TargetIntegration)
if err != nil {
return err
}
integration, err = entry.ToAPI(ctx, tx.Tx())
return err
})
if err != nil {
return fmt.Errorf("Failed to load network integration %q: %w", peer.TargetIntegration, err)
}
// Get ICNB.
icnb, err := networkOVN.NewICNB(integration.Config["ovn.northbound_connection"], integration.Config["ovn.ca_cert"], integration.Config["ovn.client_cert"], integration.Config["ovn.client_key"])
if err != nil {
return err
}
// Get ICSB.
icsb, err := networkOVN.NewICSB(integration.Config["ovn.southbound_connection"], integration.Config["ovn.ca_cert"], integration.Config["ovn.client_cert"], integration.Config["ovn.client_key"])
if err != nil {
return err
}
// Get the OVN AZ name.
azName, err := n.ovnnb.GetName(ctx)
if err != nil {
return err
}
// Get the list of interconnect gateways.
gateways, err := icsb.GetGateways(ctx, azName)
if err != nil {
return err
}
if len(gateways) == 0 {
return errors.New("No chassis gateways available for interconnect")
}
// Determine the transit switch name.
pattern := integration.Config["ovn.transit.pattern"]
if pattern == "" {
pattern = "ts-incus-{{ integrationName }}-{{ projectName }}-{{ networkName }}"
}
tsNameRendered, err := internalUtil.RenderTemplate(pattern, pongo2.Context{
"projectName": n.project,
"networkName": n.name,
"integrationName": integration.Name,
"peerName": peer.Name,
})
if err != nil {
return err
}
tsName := networkOVN.OVNSwitch(tsNameRendered)
// Determine the chassis group name.
cgName := networkOVN.OVNChassisGroup(tsName)
// Create the chassis group.
err = n.ovnnb.CreateChassisGroup(ctx, cgName, false)
if err != nil {
return err
}
reverter.Add(func() { _ = n.ovnnb.DeleteChassisGroup(ctx, cgName) })
// Seed the stable random number generator with the transit switch name.
// This should cause a reasonable spread of networks on the available IC gateway chassis.
r, err := localUtil.GetStableRandomGenerator(tsNameRendered)
if err != nil {
return fmt.Errorf("Failed generating stable random chassis group priority: %w", err)
}
// Assign some priorities.
for _, gateway := range gateways {
err = n.ovnnb.SetChassisGroupPriority(ctx, cgName, gateway, r.Intn(ovnChassisPriorityMax+1))
if err != nil {
return err
}
}
// Create the transit switch if it doesn't exist already.
err = icnb.CreateTransitSwitch(ctx, string(tsName), true)
if err != nil {
return err
}
// Check that the switch appeared on the local OVN.
found := false
for range 10 {
// Try to get the switch.
logicalSwitch, err := n.ovnnb.GetLogicalSwitch(ctx, tsName)
if err != nil && !errors.Is(err, networkOVN.ErrNotFound) {
return err
}
if logicalSwitch != nil {
found = true
break
}
time.Sleep(time.Second)
}
if !found {
return errors.New("New transit switch didn't appear within 10s")
}
// Get router MAC address.
routerMAC, err := n.getRouterMAC()
if err != nil {
return err
}
// Get bridge MTU.
bridgeMTU := int(n.getBridgeMTU())
if bridgeMTU == 0 {
bridgeMTU = 1500
}
// Get peering addresses.
ipv4Net, ipv6Net, err := icnb.CreateTransitSwitchAllocation(ctx, string(tsName), azName)
if err != nil {
return err
}
// Determine logical router port name.
lrpName := networkOVN.OVNRouterPort(tsName)
// Create the logical router port.
err = n.ovnnb.CreateLogicalRouterPort(ctx, n.getRouterName(), lrpName, routerMAC, uint32(bridgeMTU), []*net.IPNet{ipv4Net, ipv6Net}, cgName, false)
if err != nil {
return err
}
reverter.Add(func() { _ = n.ovnnb.DeleteLogicalRouterPort(ctx, n.getRouterName(), lrpName) })
// Create the logical switch port.
lspOpts := &networkOVN.OVNSwitchPortOpts{RouterPort: lrpName}
err = n.ovnnb.CreateLogicalSwitchPort(ctx, tsName, networkOVN.OVNSwitchPort(fmt.Sprintf("%s-%s", tsName, azName)), lspOpts, false)
if err != nil {
return err
}
reverter.Add(func() {
_ = n.ovnnb.DeleteLogicalSwitchPort(ctx, tsName, networkOVN.OVNSwitchPort(fmt.Sprintf("%s-%s", tsName, azName)))
})
reverter.Success()
return nil
}
// PeerCreate creates a network peering.
func (n *ovn) PeerCreate(peer api.NetworkPeersPost) error {
reverter := revert.New()
defer reverter.Fail()
// Default type is local.
if peer.Type == "" {
peer.Type = "local"
}
// Perform create-time validation.
if peer.Type == "local" {
// Default to network's project if target project not specified.
if peer.TargetProject == "" {
peer.TargetProject = n.Project()
}
// Target network name is required.
if peer.TargetNetwork == "" {
return api.StatusErrorf(http.StatusBadRequest, "Target network is required")
}
} else if peer.Type == "remote" {
// Target integration name is required.
if peer.TargetIntegration == "" {
return api.StatusErrorf(http.StatusBadRequest, "Target integration is required")
}
}
// Look for an existing entry.
var peers map[int64]*api.NetworkPeer
err := n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
var err error
// Use generated function to get peers.
netID := n.ID()
filter := dbCluster.NetworkPeerFilter{NetworkID: &netID}
dbPeers, err := dbCluster.GetNetworkPeers(ctx, tx.Tx(), filter)
if err != nil {
return fmt.Errorf("Failed loading network peer DB objects: %w", err)
}
// Convert DB objects to API objects and build the map.
peers = make(map[int64]*api.NetworkPeer, len(dbPeers))
for _, dbPeer := range dbPeers {
peer, err := dbPeer.ToAPI(ctx, tx.Tx())
if err != nil {
return fmt.Errorf("Failed converting network peer DB object to API object: %w", err)
}
peers[dbPeer.ID] = peer
}
return nil
})
if err != nil {
return err
}
for _, existingPeer := range peers {
if peer.Name == existingPeer.Name {
return api.StatusErrorf(http.StatusConflict, "A peer for that name already exists")
}
if peer.Type == "local" && peer.TargetProject == existingPeer.TargetProject && peer.TargetNetwork == existingPeer.TargetNetwork {
return api.StatusErrorf(http.StatusConflict, "A peer for that target network already exists")
}
}
// Perform general (create and update) validation.
err = n.peerValidate(peer.Name, &peer.NetworkPeerPut)
if err != nil {
return err
}
var peerID int64
var mutualExists bool
err = n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error { // Create peer DB record.
record := dbCluster.NetworkPeer{
NetworkID: n.ID(),
Name: peer.Name,
Description: peer.Description,
Type: dbCluster.NetworkPeerTypes[peer.Type],
}
switch peer.Type {
case "remote":
integrationID, err := dbCluster.GetNetworkIntegrationID(ctx, tx.Tx(), peer.TargetIntegration)
if err != nil {
return err
}
id := sql.NullInt64{}
err = id.Scan(integrationID)
if err != nil {
return err
}
record.TargetNetworkIntegrationID = id
case "local":
// Check if target peer already exists.
peers, err := dbCluster.GetNetworkPeers(ctx, tx.Tx(), dbCluster.NetworkPeerFilter{
Type: &record.Type,
TargetNetworkProject: &n.project,
TargetNetworkName: &n.name,
})
if err != nil && !errors.Is(err, sql.ErrNoRows) {
return err
}
if len(peers) == 1 {
// Update the target peer.
peer := peers[0]
empty := sql.NullString{}
peer.TargetNetworkProject = empty
peer.TargetNetworkName = empty
targetID := sql.NullInt64{}
err = targetID.Scan(n.id)
if err != nil {
return err
}
peer.TargetNetworkID = targetID
err = dbCluster.UpdateNetworkPeer(ctx, tx.Tx(), peer.NetworkID, peer.Name, peer)
if err != nil {
return err
}
// Set our target network ID to match.
id := sql.NullInt64{}
err = id.Scan(peer.NetworkID)
if err != nil {
return err
}
record.TargetNetworkID = id
mutualExists = true
} else if len(peers) == 0 {
networkProjectName := sql.NullString{}
err = networkProjectName.Scan(peer.TargetProject)
if err != nil {
return err
}
networkName := sql.NullString{}
err = networkName.Scan(peer.TargetNetwork)
if err != nil {
return err
}
record.TargetNetworkProject = networkProjectName
record.TargetNetworkName = networkName
} else {
return errors.New("More than one matching network peer was found")
}
}
peerID, err = dbCluster.CreateNetworkPeer(ctx, tx.Tx(), record)
if err != nil {
return err
}
return nil
})
if err != nil {
return err
}
reverter.Add(func() {
_ = n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
err := dbCluster.DeleteNetworkPeer(ctx, tx.Tx(), n.ID(), peerID)
if errors.Is(err, dbCluster.ErrNotFound) {
return nil
}
return err
})
})
// Apply the OVN configuration.
if peer.Type == "local" && mutualExists {
err := n.localPeerCreate(peer)
if err != nil {
return err
}
} else if peer.Type == "remote" {
err := n.remotePeerCreate(peer)
if err != nil {
return err
}
}
reverter.Success()
return nil
}
// peerGetLocalOpts returns peering options prefilled with local router and local NIC routes config.
// It can then be modified with the target peering network options.
func (n *ovn) peerGetLocalOpts(localNICRoutes []net.IPNet) (*networkOVN.OVNRouterPeering, error) {
localRouterPortMAC, err := n.getRouterMAC()
if err != nil {
return nil, fmt.Errorf("Failed getting router MAC address: %w", err)
}
opts := networkOVN.OVNRouterPeering{
LocalRouter: n.getRouterName(),
LocalRouterPortMAC: localRouterPortMAC,
TargetRouterRoutes: localNICRoutes, // Pre-fill with local NIC routes.
}
routerIntPortIPv4, routerIntPortIPv4Net, err := n.parseRouterIntPortIPv4Net()
if err != nil {
return nil, fmt.Errorf("Failed parsing local router's peering port IPv4 net: %w", err)
}
if routerIntPortIPv4 != nil && routerIntPortIPv4Net != nil {
// Add a copy of the CIDR subnet to the target router's routes.
opts.TargetRouterRoutes = append(opts.TargetRouterRoutes, *routerIntPortIPv4Net)
// Convert the IPNet to include the specific router IP with a single host subnet.
routerIntPortIPv4Net.IP = routerIntPortIPv4
routerIntPortIPv4Net.Mask = net.CIDRMask(32, 32)
opts.LocalRouterPortIPs = append(opts.LocalRouterPortIPs, *routerIntPortIPv4Net)
}
routerIntPortIPv6, routerIntPortIPv6Net, err := n.parseRouterIntPortIPv6Net()
if err != nil {
return nil, fmt.Errorf("Failed parsing local router's peering port IPv6 net: %w", err)
}
if routerIntPortIPv6 != nil && routerIntPortIPv6Net != nil {
// Add a copy of the CIDR subnet to the target router's routers.
opts.TargetRouterRoutes = append(opts.TargetRouterRoutes, *routerIntPortIPv6Net)
// Convert the IPNet to include the specific router IP with a single host subnet.
routerIntPortIPv6Net.IP = routerIntPortIPv6
routerIntPortIPv6Net.Mask = net.CIDRMask(128, 128)
opts.LocalRouterPortIPs = append(opts.LocalRouterPortIPs, *routerIntPortIPv6Net)
}
return &opts, err
}
// peerSetup applies the network peering configuration to both networks.
// Accepts an OVN client, a target OVN network, and a set of OVNRouterPeering options pre-filled with local config.
func (n *ovn) peerSetup(ovnnb *networkOVN.NB, targetOVNNet *ovn, opts networkOVN.OVNRouterPeering) error {
targetRouterMAC, err := targetOVNNet.getRouterMAC()
if err != nil {
return fmt.Errorf("Failed getting target router MAC address: %w", err)
}
// Populate config based on target network.
opts.LocalRouterPort = n.getLogicalRouterPeerPortName(targetOVNNet.ID())
opts.TargetRouter = targetOVNNet.getRouterName()
opts.TargetRouterPort = targetOVNNet.getLogicalRouterPeerPortName(n.ID())
opts.TargetRouterPortMAC = targetRouterMAC
routerIntPortIPv4, routerIntPortIPv4Net, err := targetOVNNet.parseRouterIntPortIPv4Net()
if err != nil {
return fmt.Errorf("Failed parsing target router's peering port IPv4 net: %w", err)
}
if routerIntPortIPv4 != nil && routerIntPortIPv4Net != nil {
// Add a copy of the CIDR subnet to the local router's routers.
opts.LocalRouterRoutes = append(opts.LocalRouterRoutes, *routerIntPortIPv4Net)
// Convert the IPNet to include the specific router IP with a single host subnet.
routerIntPortIPv4Net.IP = routerIntPortIPv4
routerIntPortIPv4Net.Mask = net.CIDRMask(32, 32)
opts.TargetRouterPortIPs = append(opts.TargetRouterPortIPs, *routerIntPortIPv4Net)
}
routerIntPortIPv6, routerIntPortIPv6Net, err := targetOVNNet.parseRouterIntPortIPv6Net()
if err != nil {
return fmt.Errorf("Failed parsing target router's peering port IPv6 net: %w", err)
}
if routerIntPortIPv6 != nil && routerIntPortIPv6Net != nil {
// Add a copy of the CIDR subnet to the local router's routers.
opts.LocalRouterRoutes = append(opts.LocalRouterRoutes, *routerIntPortIPv6Net)
// Convert the IPNet to include the specific router IP with a single host subnet.
routerIntPortIPv6Net.IP = routerIntPortIPv6
routerIntPortIPv6Net.Mask = net.CIDRMask(128, 128)
opts.TargetRouterPortIPs = append(opts.TargetRouterPortIPs, *routerIntPortIPv6Net)
}
// Get list of active switch ports (avoids repeated querying of OVN NB).
activeTargetNICPorts, err := n.ovnnb.GetLogicalSwitchPorts(context.TODO(), targetOVNNet.getIntSwitchName())
if err != nil {
return fmt.Errorf("Failed getting active NIC ports: %w", err)
}
// Get routes on instance NICs connected to target network to be added as routes to local network.
err = UsedByInstanceDevices(n.state, targetOVNNet.Project(), targetOVNNet.Name(), targetOVNNet.Type(), func(inst db.InstanceArgs, nicName string, nicConfig map[string]string) error {
instancePortName := targetOVNNet.getInstanceDevicePortName(inst.Config["volatile.uuid"], nicName)
_, found := activeTargetNICPorts[instancePortName]
if !found {
return nil // Don't add config for instance NICs that aren't started.
}
opts.LocalRouterRoutes = append(opts.LocalRouterRoutes, n.instanceNICGetRoutes(nicConfig)...)
return nil
})
if err != nil {
return fmt.Errorf("Failed getting instance NIC routes on target network: %w", err)
}
// Ensure routes are added to target switch address sets.
err = n.ovnnb.UpdateAddressSetAdd(context.TODO(), acl.OVNIntSwitchPortGroupAddressSetPrefix(targetOVNNet.ID()), opts.LocalRouterRoutes...)
if err != nil {
return fmt.Errorf("Failed adding target switch subnet address set entries: %w", err)
}
err = targetOVNNet.logicalRouterPolicySetup(n.ovnnb)
if err != nil {
return fmt.Errorf("Failed applying target router security policy: %w", err)
}
err = n.ovnnb.CreateLogicalRouterPeering(context.TODO(), opts)
if err != nil {
return fmt.Errorf("Failed applying OVN network peering: %w", err)
}
return nil
}
// PeerUpdate updates a network peering.
func (n *ovn) PeerUpdate(peerName string, req api.NetworkPeerPut) error {
reverter := revert.New()
defer reverter.Fail()
var curPeer *api.NetworkPeer
var dbCurPeer *dbCluster.NetworkPeer
err := n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
var err error
dbCurPeer, err = dbCluster.GetNetworkPeer(ctx, tx.Tx(), n.id, peerName)
if err != nil {
return fmt.Errorf("Failed getting network peer DB object: %w", err)
}
curPeer, err = dbCurPeer.ToAPI(ctx, tx.Tx())
if err != nil {
return fmt.Errorf("Failed converting network peer DB object to API object: %w", err)
}
return nil
})
if err != nil {
return err
}
err = n.peerValidate(peerName, &req)
if err != nil {
return err
}
curPeerEtagHash, err := localUtil.EtagHash(curPeer.Etag())
if err != nil {
return err
}
newPeer := api.NetworkPeer{
Name: curPeer.Name,
NetworkPeerPut: req,
}
newPeerEtagHash, err := localUtil.EtagHash(newPeer.Etag())
if err != nil {
return err
}
if curPeerEtagHash == newPeerEtagHash {
return nil // Nothing has changed.
}
err = n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
// Update the description field from the input.
dbCurPeer.Description = newPeer.Description
// Update the main peer object.
err = dbCluster.UpdateNetworkPeer(ctx, tx.Tx(), n.id, dbCurPeer.Name, *dbCurPeer)
if err != nil {
return fmt.Errorf("Failed to update network peer: %w", err)
}
// Update the peer configuration.
err = dbCluster.UpdateNetworkPeerConfig(ctx, tx.Tx(), dbCurPeer.ID, newPeer.Config)
if err != nil {
return fmt.Errorf("Failed to update network peer config: %w", err)
}
return nil
})
if err != nil {
return err
}
reverter.Success()
return nil
}
// localPeerDelete deletes a network peering with another local network.
func (n *ovn) localPeerDelete(peer *api.NetworkPeer) error {
targetNet, err := LoadByName(n.state, peer.TargetProject, peer.TargetNetwork)
if err != nil {
return fmt.Errorf("Failed loading target network: %w", err)
}
targetOVNNet, ok := targetNet.(*ovn)
if !ok {
return errors.New("Target network is not ovn interface type")
}
opts := networkOVN.OVNRouterPeering{
LocalRouter: n.getRouterName(),
LocalRouterPort: n.getLogicalRouterPeerPortName(targetOVNNet.ID()),
TargetRouter: targetOVNNet.getRouterName(),
TargetRouterPort: targetOVNNet.getLogicalRouterPeerPortName(n.ID()),
}
err = n.ovnnb.DeleteLogicalRouterPeering(context.TODO(), opts)
if err != nil {
return fmt.Errorf("Failed deleting OVN network peering: %w", err)
}
err = n.logicalRouterPolicySetup(n.ovnnb, targetOVNNet.ID())
if err != nil {
return fmt.Errorf("Failed applying local router security policy: %w", err)
}
err = targetOVNNet.logicalRouterPolicySetup(n.ovnnb, n.ID())
if err != nil {
return fmt.Errorf("Failed applying target router security policy: %w", err)
}
return nil
}
// remotePeerDelete deletes a network peering with an OVN-IC.
func (n *ovn) remotePeerDelete(peer *api.NetworkPeer) error {
ctx := context.TODO()
// Load the integration.
var integration *api.NetworkIntegration
err := n.state.DB.Cluster.Transaction(ctx, func(ctx context.Context, tx *db.ClusterTx) error {
entry, err := dbCluster.GetNetworkIntegration(ctx, tx.Tx(), peer.TargetIntegration)
if err != nil {
return err
}
integration, err = entry.ToAPI(ctx, tx.Tx())
return err
})
if err != nil {
return fmt.Errorf("Failed to load network integration %q: %w", peer.TargetIntegration, err)
}
// Get ICNB.
icnb, err := networkOVN.NewICNB(integration.Config["ovn.northbound_connection"], integration.Config["ovn.ca_cert"], integration.Config["ovn.client_cert"], integration.Config["ovn.client_key"])
if err != nil {
return err
}
// Get the OVN AZ name.
azName, err := n.ovnnb.GetName(ctx)
if err != nil {
return err
}
// Determine the transit switch name.
pattern := integration.Config["ovn.transit.pattern"]
if pattern == "" {
pattern = "ts-incus-{{ integrationName }}-{{ projectName }}-{{ networkName }}"
}
tsNameRendered, err := internalUtil.RenderTemplate(pattern, pongo2.Context{
"projectName": n.project,
"networkName": n.name,
"integrationName": integration.Name,
"peerName": peer.Name,
})
if err != nil {
return err
}
tsName := networkOVN.OVNSwitch(tsNameRendered)
// Delete logical switch port
err = n.ovnnb.DeleteLogicalSwitchPort(ctx, tsName, networkOVN.OVNSwitchPort(fmt.Sprintf("%s-%s", tsName, azName)))
if err != nil {
return err
}
// Determine logical router port name.
lrpName := networkOVN.OVNRouterPort(tsName)
// Delete logical router port
err = n.ovnnb.DeleteLogicalRouterPort(ctx, n.getRouterName(), lrpName)
if err != nil {
return err
}
// Determine the chassis group name.
cgName := networkOVN.OVNChassisGroup(tsName)
// Delete chassis group.
err = n.ovnnb.DeleteChassisGroup(ctx, cgName)
if err != nil && !errors.Is(err, networkOVN.ErrNotManaged) {
return err
}
// Delete transit switch if empty
icSwitch, err := n.ovnnb.GetLogicalSwitch(ctx, tsName)
if err != nil {
return err
}
if len(icSwitch.Ports) == 0 {
err = icnb.DeleteTransitSwitch(ctx, string(tsName), false)
if err != nil && !errors.Is(err, networkOVN.ErrNotManaged) {
return err
}
} else {
// Get the OVN AZ name.
azName, err := n.ovnnb.GetName(ctx)
if err != nil {
return err
}
// Release peering addresses.
err = icnb.DeleteTransitSwitchAllocation(ctx, string(tsName), azName)
if err != nil {
return err
}
}
return nil
}
// PeerDelete deletes a network peering.
func (n *ovn) PeerDelete(peerName string) error {
var peerID int64
var peer *api.NetworkPeer
err := n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
dbPeer, err := dbCluster.GetNetworkPeer(ctx, tx.Tx(), n.id, peerName)
if err != nil {
return fmt.Errorf("Failed getting network peer DB object: %w", err)
}
peerID = dbPeer.ID
peer, err = dbPeer.ToAPI(ctx, tx.Tx())
if err != nil {
return fmt.Errorf("Failed converting network peer DB object to API object: %w", err)
}
return nil
})
if err != nil {
return err
}
isUsed, err := n.peerIsUsed(peer.Name)
if err != nil {
return err
}
if isUsed {
return errors.New("Cannot delete a peer that is in use")
}
if peer.Status == api.NetworkStatusCreated {
if peer.Type == "local" {
err := n.localPeerDelete(peer)
if err != nil {
return err
}
} else if peer.Type == "remote" {
err := n.remotePeerDelete(peer)
if err != nil {
return err
}
}
}
err = n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
// Deactivate any existing peer.
if peer.Type == "local" {
peers, err := dbCluster.GetNetworkPeers(ctx, tx.Tx(), dbCluster.NetworkPeerFilter{TargetNetworkID: &n.id})
if err != nil && !errors.Is(err, sql.ErrNoRows) {
return err
}
for _, peer := range peers {
peer.TargetNetworkID = sql.NullInt64{}
err = dbCluster.UpdateNetworkPeer(ctx, tx.Tx(), peer.NetworkID, peer.Name, peer)
if err != nil {
return err
}
}
}
// Delete the peer.
err := dbCluster.DeleteNetworkPeer(ctx, tx.Tx(), n.id, peerID)
if err != nil {
return err
}
return nil
})
if err != nil {
return err
}
return nil
}
// forPeers runs f for each target peer network that this network is connected to.
func (n *ovn) forPeers(f func(targetOVNNet *ovn) error) error {
var peers map[int64]*api.NetworkPeer
err := n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
var err error
// Use generated function to get peers.
netID := n.ID()
filter := dbCluster.NetworkPeerFilter{NetworkID: &netID}
dbPeers, err := dbCluster.GetNetworkPeers(ctx, tx.Tx(), filter)
if err != nil {
return fmt.Errorf("Failed loading network peer DB objects: %w", err)
}
// Convert DB objects to API objects and build the map.
peers = make(map[int64]*api.NetworkPeer, len(dbPeers))
for _, dbPeer := range dbPeers {
peer, err := dbPeer.ToAPI(ctx, tx.Tx())
if err != nil {
return fmt.Errorf("Failed converting network peer DB object to API object: %w", err)
}
peers[dbPeer.ID] = peer
}
return nil
})
if err != nil {
return err
}
for _, peer := range peers {
// Skip partially defined peers.
if peer.Status != api.NetworkStatusCreated {
continue
}
// Skip remote peers (no local networks to load).
if peer.Type == "remote" {
continue
}
targetNet, err := LoadByName(n.state, peer.TargetProject, peer.TargetNetwork)
if err != nil {
return fmt.Errorf("Failed loading target network: %w", err)
}
targetOVNNet, ok := targetNet.(*ovn)
if !ok {
return errors.New("Target network is not ovn interface type")
}
err = f(targetOVNNet)
if err != nil {
return err
}
}
return nil
}
// loadBalancerBGPSetupPrefixes exports external load balancer addresses as prefixes.
func (n *ovn) loadBalancerBGPSetupPrefixes() error {
listenAddresses := []string{}
err := n.state.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
networkID := n.ID()
dbLoadBalancers, err := dbCluster.GetNetworkLoadBalancers(ctx, tx.Tx(), dbCluster.NetworkLoadBalancerFilter{
NetworkID: &networkID,
})
if err != nil {
return err
}
for _, lb := range dbLoadBalancers {
listenAddresses = append(listenAddresses, lb.ListenAddress)
}
return nil
})
if err != nil {
return fmt.Errorf("Failed loading network forwards: %w", err)
}
listenAddressesByFamily := map[uint][]string{
4: make([]string, 0),
6: make([]string, 0),
}
for _, listenAddress := range listenAddresses {
if strings.Contains(listenAddress, ":") {
listenAddressesByFamily[6] = append(listenAddressesByFamily[6], listenAddress)
} else {
listenAddressesByFamily[4] = append(listenAddressesByFamily[4], listenAddress)
}
}
// Use load balancer specific owner string (different from the network prefixes) so that these can be
// reapplied independently of the network's own prefixes.
bgpOwner := fmt.Sprintf("network_%d_load_balancer", n.id)
// Clear existing address load balancer prefixes for network.
err = n.state.BGP.RemovePrefixByOwner(bgpOwner)
if err != nil {
return err
}
// Add the new prefixes.
for _, ipVersion := range []uint{4, 6} {
nextHopAddr := n.bgpNextHopAddress(ipVersion)
natEnabled := util.IsTrue(n.config[fmt.Sprintf("ipv%d.nat", ipVersion)])
_, netSubnet, _ := net.ParseCIDR(n.config[fmt.Sprintf("ipv%d.address", ipVersion)])
routeSubnetSize := 128
if ipVersion == 4 {
routeSubnetSize = 32
}
// Export external forward listen addresses.
for _, listenAddress := range listenAddressesByFamily[ipVersion] {
listenAddr := net.ParseIP(listenAddress)
// Don't export internal address forwards (those inside the NAT enabled network's subnet).
if natEnabled && netSubnet != nil && netSubnet.Contains(listenAddr) {
continue
}
// Check health of load-balancer (if enabled).
online := false
for _, protocol := range []string{"tcp", "udp"} {
lb, err := n.ovnnb.GetLoadBalancer(context.TODO(), networkOVN.OVNLoadBalancer(fmt.Sprintf("incus-net%d-lb-%s-%s", n.id, listenAddr.String(), protocol)))
if err != nil {
continue
}
lbOnline, err := n.ovnsb.CheckLoadBalancerOnline(context.TODO(), *lb)
if err != nil {
continue
}
if lbOnline {
online = true
break
}
}
if !online {
continue
}
_, ipRouteSubnet, err := net.ParseCIDR(fmt.Sprintf("%s/%d", listenAddr.String(), routeSubnetSize))
if err != nil {
return err
}
err = n.state.BGP.AddPrefix(*ipRouteSubnet, nextHopAddr, bgpOwner)
if err != nil {
return err
}
}
}
return nil
}
|