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
|
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"maps"
"net"
"net/http"
"net/url"
"slices"
"strconv"
"strings"
"sync"
"time"
"github.com/gorilla/mux"
"github.com/lxc/incus/v6/internal/osapi"
incus "github.com/lxc/incus/v6/client"
"github.com/lxc/incus/v6/internal/filter"
"github.com/lxc/incus/v6/internal/server/auth"
"github.com/lxc/incus/v6/internal/server/cluster"
clusterRequest "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"
"github.com/lxc/incus/v6/internal/server/db/warningtype"
"github.com/lxc/incus/v6/internal/server/instance"
"github.com/lxc/incus/v6/internal/server/instance/instancetype"
"github.com/lxc/incus/v6/internal/server/lifecycle"
"github.com/lxc/incus/v6/internal/server/network"
"github.com/lxc/incus/v6/internal/server/project"
"github.com/lxc/incus/v6/internal/server/request"
"github.com/lxc/incus/v6/internal/server/response"
"github.com/lxc/incus/v6/internal/server/state"
localUtil "github.com/lxc/incus/v6/internal/server/util"
"github.com/lxc/incus/v6/internal/server/warnings"
"github.com/lxc/incus/v6/internal/version"
"github.com/lxc/incus/v6/shared/api"
"github.com/lxc/incus/v6/shared/logger"
"github.com/lxc/incus/v6/shared/resources"
"github.com/lxc/incus/v6/shared/revert"
"github.com/lxc/incus/v6/shared/util"
"github.com/lxc/incus/v6/shared/validate"
)
// Lock to prevent concurrent networks creation.
var networkCreateLock sync.Mutex
var networksCmd = APIEndpoint{
Path: "networks",
Get: APIEndpointAction{Handler: networksGet, AccessHandler: allowAuthenticated},
Post: APIEndpointAction{Handler: networksPost, AccessHandler: allowPermission(auth.ObjectTypeProject, auth.EntitlementCanCreateNetworks)},
}
var networkCmd = APIEndpoint{
Path: "networks/{networkName}",
Delete: APIEndpointAction{Handler: networkDelete, AccessHandler: allowPermission(auth.ObjectTypeNetwork, auth.EntitlementCanEdit, "networkName")},
Get: APIEndpointAction{Handler: networkGet, AccessHandler: allowAuthenticated},
Patch: APIEndpointAction{Handler: networkPatch, AccessHandler: allowPermission(auth.ObjectTypeNetwork, auth.EntitlementCanEdit, "networkName")},
Post: APIEndpointAction{Handler: networkPost, AccessHandler: allowPermission(auth.ObjectTypeNetwork, auth.EntitlementCanEdit, "networkName")},
Put: APIEndpointAction{Handler: networkPut, AccessHandler: allowPermission(auth.ObjectTypeNetwork, auth.EntitlementCanEdit, "networkName")},
}
var networkLeasesCmd = APIEndpoint{
Path: "networks/{networkName}/leases",
Get: APIEndpointAction{Handler: networkLeasesGet, AccessHandler: allowPermission(auth.ObjectTypeNetwork, auth.EntitlementCanView, "networkName")},
}
var networkStateCmd = APIEndpoint{
Path: "networks/{networkName}/state",
Get: APIEndpointAction{Handler: networkStateGet, AccessHandler: allowPermission(auth.ObjectTypeNetwork, auth.EntitlementCanView, "networkName")},
}
// API endpoints
// swagger:operation GET /1.0/networks networks networks_get
//
// Get the networks
//
// Returns a list of networks (URLs).
//
// ---
// produces:
// - application/json
// parameters:
// - in: query
// name: project
// description: Project name
// type: string
// example: default
// - in: query
// name: all-projects
// description: Retrieve networks from all projects
// type: boolean
// example: true
// - in: query
// name: filter
// description: Collection filter
// type: string
// example: default
// responses:
// "200":
// description: API endpoints
// schema:
// type: object
// description: Sync response
// properties:
// type:
// type: string
// description: Response type
// example: sync
// status:
// type: string
// description: Status description
// example: Success
// status_code:
// type: integer
// description: Status code
// example: 200
// metadata:
// type: array
// description: List of endpoints
// items:
// type: string
// example: |-
// [
// "/1.0/networks/mybr0",
// "/1.0/networks/mybr1"
// ]
// "403":
// $ref: "#/responses/Forbidden"
// "500":
// $ref: "#/responses/InternalServerError"
// swagger:operation GET /1.0/networks?recursion=1 networks networks_get_recursion1
//
// Get the networks
//
// Returns a list of networks (structs).
//
// ---
// produces:
// - application/json
// parameters:
// - in: query
// name: project
// description: Project name
// type: string
// example: default
// - in: query
// name: all-projects
// description: Retrieve networks from all projects
// type: boolean
// example: true
// - in: query
// name: filter
// description: Collection filter
// type: string
// example: default
// responses:
// "200":
// description: API endpoints
// schema:
// type: object
// description: Sync response
// properties:
// type:
// type: string
// description: Response type
// example: sync
// status:
// type: string
// description: Status description
// example: Success
// status_code:
// type: integer
// description: Status code
// example: 200
// metadata:
// type: array
// description: List of networks
// items:
// $ref: "#/definitions/Network"
// "403":
// $ref: "#/responses/Forbidden"
// "500":
// $ref: "#/responses/InternalServerError"
func networksGet(d *Daemon, r *http.Request) response.Response {
s := d.State()
projectName, reqProject, err := project.NetworkProject(s.DB.Cluster, request.ProjectParam(r))
if err != nil {
return response.SmartError(err)
}
recursion := localUtil.IsRecursionRequest(r)
// Parse filter value.
filterStr := r.FormValue("filter")
clauses, err := filter.Parse(filterStr, filter.QueryOperatorSet())
if err != nil {
return response.BadRequest(fmt.Errorf("Invalid filter: %w", err))
}
mustLoadObjects := recursion || (clauses != nil && len(clauses.Clauses) > 0)
allProjects := util.IsTrue(r.FormValue("all-projects"))
unmanagedNetworkNames := []string{}
var networkNames map[string][]string
err = s.DB.Cluster.Transaction(r.Context(), func(ctx context.Context, tx *db.ClusterTx) error {
if allProjects {
// Get list of managed networks from all projects.
networkNames, err = tx.GetNetworksAllProjects(ctx)
if err != nil {
return err
}
} else {
// Get list of managed networks (that may or may not have network interfaces on the host).
networks, err := tx.GetNetworks(ctx, projectName)
if err != nil {
return err
}
networkNames = map[string][]string{}
networkNames[projectName] = networks
}
return nil
})
if err != nil {
return response.SmartError(err)
}
// Get list of actual network interfaces on the host as well if the effective project is Default.
if projectName == api.ProjectDefaultName {
if s.OS.IncusOS {
// When running on Incus OS, limit the list to those with the "instances" role.
client := &http.Client{
Transport: &http.Transport{
DialContext: func(_ context.Context, _, _ string) (net.Conn, error) {
return net.Dial("unix", "/run/incus-os/unix.socket")
},
},
}
// Query the OS network state.
resp, err := client.Get("http://incus-os/1.0/system/network")
if err != nil {
return response.InternalError(err)
}
defer resp.Body.Close()
// Convert to an Incus response struct.
apiResp := &api.Response{}
err = json.NewDecoder(resp.Body).Decode(apiResp)
if err != nil {
return response.InternalError(err)
}
// Quick validation.
if apiResp.Type != "sync" || apiResp.StatusCode != http.StatusOK {
return response.InternalError(errors.New("Bad network state from Incus OS"))
}
// Parse the response.
ns := &osapi.SystemNetwork{}
err = apiResp.MetadataAsStruct(ns)
if err != nil {
return response.InternalError(err)
}
// Get the interfaces.
for _, iface := range ns.State.GetInterfaceNamesByRole("instances") {
// Append to the list of networks if a managed network of same name doesn't exist.
if !slices.Contains(networkNames[projectName], iface) {
networkNames[projectName] = append(networkNames[projectName], iface)
unmanagedNetworkNames = append(unmanagedNetworkNames, iface)
}
}
} else {
ifaces, err := net.Interfaces()
if err != nil {
return response.InternalError(err)
}
for _, iface := range ifaces {
// Ignore veth pairs (for performance reasons).
if strings.HasPrefix(iface.Name, "veth") {
continue
}
// Append to the list of networks if a managed network of same name doesn't exist.
if !slices.Contains(networkNames[projectName], iface.Name) {
networkNames[projectName] = append(networkNames[projectName], iface.Name)
unmanagedNetworkNames = append(unmanagedNetworkNames, iface.Name)
}
}
}
}
linkResults := make([]string, 0)
fullResults := make([]api.Network, 0)
for projectName, networks := range networkNames {
for _, networkName := range networks {
if mustLoadObjects {
netInfo, err := doNetworkGet(s, r, s.ServerClustered, projectName, reqProject.Config, networkName)
if err != nil {
continue
}
if clauses != nil && len(clauses.Clauses) > 0 {
match, err := filter.Match(netInfo, *clauses)
if err != nil {
return response.SmartError(err)
}
if !match {
continue
}
}
fullResults = append(fullResults, netInfo)
} else {
ok, err := canAccessNetwork(s, r, projectName, reqProject.Config, networkName, !slices.Contains(unmanagedNetworkNames, networkName))
if err != nil {
return response.SmartError(err)
}
if !ok {
continue
}
}
linkResults = append(linkResults, fmt.Sprintf("/%s/networks/%s", version.APIVersion, networkName))
}
}
if !recursion {
return response.SyncResponse(true, linkResults)
}
return response.SyncResponse(true, fullResults)
}
// swagger:operation POST /1.0/networks networks networks_post
//
// Add a network
//
// Creates a new network.
// When clustered, most network types require individual POST for each cluster member prior to a global POST.
//
// ---
// consumes:
// - application/json
// produces:
// - application/json
// parameters:
// - in: query
// name: project
// description: Project name
// type: string
// example: default
// - in: query
// name: target
// description: Cluster member name
// type: string
// example: server01
// - in: body
// name: network
// description: Network
// required: true
// schema:
// $ref: "#/definitions/NetworksPost"
// responses:
// "200":
// $ref: "#/responses/EmptySyncResponse"
// "400":
// $ref: "#/responses/BadRequest"
// "403":
// $ref: "#/responses/Forbidden"
// "500":
// $ref: "#/responses/InternalServerError"
func networksPost(d *Daemon, r *http.Request) response.Response {
s := d.State()
projectName, reqProject, err := project.NetworkProject(s.DB.Cluster, request.ProjectParam(r))
if err != nil {
return response.SmartError(err)
}
networkCreateLock.Lock()
defer networkCreateLock.Unlock()
req := api.NetworksPost{}
// Parse the request.
err = json.NewDecoder(r.Body).Decode(&req)
if err != nil {
return response.BadRequest(err)
}
// Quick checks.
if req.Name == "" {
return response.BadRequest(errors.New("No name provided"))
}
if req.Name == "none" {
return response.BadRequest(errors.New("Invalid network name: 'none' is a reserved name"))
}
err = validate.IsAPIName(req.Name, false)
if err != nil {
return response.BadRequest(fmt.Errorf("Invalid network name: %w", err))
}
// Check if project allows access to network.
if !project.NetworkAllowed(reqProject.Config, req.Name, true) {
return response.SmartError(api.StatusErrorf(http.StatusForbidden, "Network not allowed in project"))
}
if req.Type == "" {
if projectName != api.ProjectDefaultName {
req.Type = "ovn" // Only OVN networks are allowed inside network enabled projects.
} else {
req.Type = "bridge" // Default to bridge for non-network enabled projects.
}
}
if req.Config == nil {
req.Config = map[string]string{}
}
netType, err := network.LoadByType(req.Type)
if err != nil {
return response.BadRequest(err)
}
// Driver specific name validation.
err = netType.ValidateName(req.Name)
if err != nil {
return response.BadRequest(fmt.Errorf("Invalid network name: %w", err))
}
netTypeInfo := netType.Info()
if projectName != api.ProjectDefaultName && !netTypeInfo.Projects {
return response.BadRequest(errors.New("Network type does not support non-default projects"))
}
// Check if project has limits.network and if so check we are allowed to create another network.
if projectName != api.ProjectDefaultName && reqProject.Config != nil && reqProject.Config["limits.networks"] != "" {
networksLimit, err := strconv.Atoi(reqProject.Config["limits.networks"])
if err != nil {
return response.InternalError(fmt.Errorf("Invalid project limits.network value: %w", err))
}
var networks []string
err = s.DB.Cluster.Transaction(r.Context(), func(ctx context.Context, tx *db.ClusterTx) error {
networks, err = tx.GetNetworks(ctx, projectName)
return err
})
if err != nil {
return response.InternalError(fmt.Errorf("Failed loading project's networks for limits check: %w", err))
}
// Only check network limits if the new network name doesn't exist already in networks list.
// If it does then this create request will either be for adding a target node to an existing
// pending network or it will fail anyway as it is a duplicate.
if !slices.Contains(networks, req.Name) && len(networks) >= networksLimit {
return response.BadRequest(errors.New("Networks limit has been reached for project"))
}
}
u := api.NewURL().Path(version.APIVersion, "networks", req.Name).Project(projectName)
resp := response.SyncResponseLocation(true, nil, u.String())
clientType := clusterRequest.UserAgentClientType(r.Header.Get("User-Agent"))
if isClusterNotification(r) {
n, err := network.LoadByName(s, projectName, req.Name)
if err != nil {
return response.SmartError(fmt.Errorf("Failed loading network: %w", err))
}
// This is an internal request which triggers the actual creation of the network across all nodes
// after they have been previously defined.
err = doNetworksCreate(r.Context(), s, n, clientType)
if err != nil {
return response.SmartError(err)
}
return resp
}
targetNode := request.QueryParam(r, "target")
if targetNode != "" {
if !netTypeInfo.NodeSpecificConfig {
return response.BadRequest(fmt.Errorf("Network type %q does not support member specific config", netType.Type()))
}
// A targetNode was specified, let's just define the node's network without actually creating it.
// Check that only NodeSpecificNetworkConfig keys are specified.
for key := range req.Config {
if !db.IsNodeSpecificNetworkConfig(key) {
return response.BadRequest(fmt.Errorf("Config key %q may not be used as member-specific key", key))
}
}
exists := false
err = s.DB.Cluster.Transaction(r.Context(), func(ctx context.Context, tx *db.ClusterTx) error {
_, err := tx.GetNetworkID(ctx, projectName, req.Name)
if err == nil {
exists = true
}
return tx.CreatePendingNetwork(ctx, targetNode, projectName, req.Name, req.Description, netType.DBType(), req.Config)
})
if err != nil {
if errors.Is(err, db.ErrAlreadyDefined) {
return response.Conflict(fmt.Errorf("Network %q is already defined on member %q", req.Name, targetNode))
}
return response.SmartError(err)
}
if !exists {
err = s.Authorizer.AddNetwork(r.Context(), projectName, req.Name)
if err != nil {
logger.Error("Failed to add network to authorizer", logger.Ctx{"name": req.Name, "project": projectName, "error": err})
}
n, err := network.LoadByName(s, projectName, req.Name)
if err != nil {
return response.SmartError(fmt.Errorf("Failed loading network: %w", err))
}
requestor := request.CreateRequestor(r)
s.Events.SendLifecycle(projectName, lifecycle.NetworkCreated.Event(n, requestor, nil))
}
return resp
}
var netInfo *api.Network
err = s.DB.Cluster.Transaction(r.Context(), func(ctx context.Context, tx *db.ClusterTx) error {
// Load existing network if exists, if not don't fail.
_, netInfo, _, err = tx.GetNetworkInAnyState(ctx, projectName, req.Name)
return err
})
if err != nil && !api.StatusErrorCheck(err, http.StatusNotFound) {
return response.InternalError(err)
}
// Check if we're clustered.
count, err := cluster.Count(s)
if err != nil {
return response.SmartError(err)
}
// No targetNode was specified and we're clustered or there is an existing partially created single node
// network, either way finalize the config in the db and actually create the network on all cluster nodes.
if count > 1 || (netInfo != nil && netInfo.Status != api.NetworkStatusCreated) {
// Simulate adding pending node network config when the driver doesn't support per-node config.
if !netTypeInfo.NodeSpecificConfig && clientType != clusterRequest.ClientTypeJoiner {
// Create pending entry for each node.
err = s.DB.Cluster.Transaction(r.Context(), func(ctx context.Context, tx *db.ClusterTx) error {
members, err := tx.GetNodes(ctx)
if err != nil {
return fmt.Errorf("Failed getting cluster members: %w", err)
}
for _, member := range members {
// Don't pass in any config, as these nodes don't have any node-specific
// config and we don't want to create duplicate global config.
err = tx.CreatePendingNetwork(ctx, member.Name, projectName, req.Name, req.Description, netType.DBType(), nil)
if err != nil && !errors.Is(err, db.ErrAlreadyDefined) {
return fmt.Errorf("Failed creating pending network for member %q: %w", member.Name, err)
}
}
return nil
})
if err != nil {
return response.SmartError(err)
}
// Create the authorization entry and advertise the network as existing.
err = s.Authorizer.AddNetwork(r.Context(), projectName, req.Name)
if err != nil {
logger.Error("Failed to add network to authorizer", logger.Ctx{"name": req.Name, "project": projectName, "error": err})
}
n, err := network.LoadByName(s, projectName, req.Name)
if err != nil {
return response.SmartError(fmt.Errorf("Failed loading network: %w", err))
}
requestor := request.CreateRequestor(r)
s.Events.SendLifecycle(projectName, lifecycle.NetworkCreated.Event(n, requestor, nil))
}
err = networksPostCluster(r.Context(), s, projectName, netInfo, req, clientType, netType)
if err != nil {
return response.SmartError(err)
}
return resp
}
// Non-clustered network creation.
if netInfo != nil {
return response.Conflict(fmt.Errorf("Network %q already exists", req.Name))
}
reverter := revert.New()
defer reverter.Fail()
// Populate default config.
if clientType != clusterRequest.ClientTypeJoiner {
err = netType.FillConfig(req.Config)
if err != nil {
return response.SmartError(err)
}
}
err = s.DB.Cluster.Transaction(r.Context(), func(ctx context.Context, tx *db.ClusterTx) error {
// Create the database entry.
_, err = tx.CreateNetwork(ctx, projectName, req.Name, req.Description, netType.DBType(), req.Config)
return err
})
if err != nil {
return response.SmartError(fmt.Errorf("Error inserting %q into database: %w", req.Name, err))
}
reverter.Add(func() {
_ = s.DB.Cluster.Transaction(r.Context(), func(ctx context.Context, tx *db.ClusterTx) error {
return tx.DeleteNetwork(ctx, projectName, req.Name)
})
})
n, err := network.LoadByName(s, projectName, req.Name)
if err != nil {
return response.SmartError(fmt.Errorf("Failed loading network: %w", err))
}
err = doNetworksCreate(r.Context(), s, n, clientType)
if err != nil {
return response.SmartError(err)
}
err = s.Authorizer.AddNetwork(r.Context(), projectName, req.Name)
if err != nil {
logger.Error("Failed to add network to authorizer", logger.Ctx{"name": req.Name, "project": projectName, "error": err})
}
requestor := request.CreateRequestor(r)
s.Events.SendLifecycle(projectName, lifecycle.NetworkCreated.Event(n, requestor, nil))
reverter.Success()
return resp
}
// networkPartiallyCreated returns true of supplied network has properties that indicate it has had previous
// create attempts run on it but failed on one or more nodes.
func networkPartiallyCreated(netInfo *api.Network) bool {
// If the network status is NetworkStatusErrored, this means create has been run in the past and has
// failed on one or more nodes. Hence it is partially created.
if netInfo.Status == api.NetworkStatusErrored {
return true
}
// If the network has global config keys, then it has previously been created by having its global config
// inserted, and this means it is partialled created.
for key := range netInfo.Config {
if !db.IsNodeSpecificNetworkConfig(key) {
return true
}
}
return false
}
// networksPostCluster checks that there is a pending network in the database and then attempts to setup the
// network on each node. If all nodes are successfully setup then the network's state is set to created.
// Accepts an optional existing network record, which will exist when performing subsequent re-create attempts.
func networksPostCluster(ctx context.Context, s *state.State, projectName string, netInfo *api.Network, req api.NetworksPost, clientType clusterRequest.ClientType, netType network.Type) error {
// Check that no node-specific config key has been supplied in request.
for key := range req.Config {
if db.IsNodeSpecificNetworkConfig(key) {
return fmt.Errorf("Config key %q is cluster member specific", key)
}
}
// If network already exists, perform quick checks.
if netInfo != nil {
// Check network isn't already created.
if netInfo.Status == api.NetworkStatusCreated {
return errors.New("The network is already created")
}
// Check the requested network type matches the type created when adding the local member config.
if req.Type != netInfo.Type {
return fmt.Errorf("Requested network type %q doesn't match type in existing database record %q", req.Type, netInfo.Type)
}
}
// Check that the network is properly defined, get the node-specific configs and merge with global config.
var nodeConfigs map[string]map[string]string
err := s.DB.Cluster.Transaction(ctx, func(ctx context.Context, tx *db.ClusterTx) error {
// Check if any global config exists already, if so we should not create global config again.
if netInfo != nil && networkPartiallyCreated(netInfo) {
if len(req.Config) > 0 {
return errors.New("Network already partially created. Please do not specify any global config when re-running create")
}
logger.Debug("Skipping global network create as global config already partially created", logger.Ctx{"project": projectName, "network": req.Name})
return nil
}
// Fetch the network ID.
networkID, err := tx.GetNetworkID(ctx, projectName, req.Name)
if err != nil {
return err
}
// Fetch the node-specific configs and check the network is defined for all nodes.
nodeConfigs, err = tx.NetworkNodeConfigs(ctx, networkID)
if err != nil {
return err
}
// Add default values if we are inserting global config for first time.
err = netType.FillConfig(req.Config)
if err != nil {
return err
}
// Insert the global config keys.
err = tx.CreateNetworkConfig(networkID, 0, req.Config)
if err != nil {
return err
}
// Assume failure unless we succeed later on.
return tx.NetworkErrored(projectName, req.Name)
})
if err != nil {
if response.IsNotFoundError(err) {
return errors.New("Network not pending on any node (use --target <node> first)")
}
return err
}
// Create notifier for other nodes to create the network.
notifier, err := cluster.NewNotifier(s, s.Endpoints.NetworkCert(), s.ServerCert(), cluster.NotifyAll)
if err != nil {
return err
}
// Load the network from the database for the local member.
n, err := network.LoadByName(s, projectName, req.Name)
if err != nil {
return fmt.Errorf("Failed loading network: %w", err)
}
netConfig := n.Config()
err = doNetworksCreate(ctx, s, n, clientType)
if err != nil {
return err
}
logger.Debug("Created network on local cluster member", logger.Ctx{"project": projectName, "network": req.Name, "config": netConfig})
// Remove this node's node specific config keys.
netConfig = db.StripNodeSpecificNetworkConfig(netConfig)
// Notify other nodes to create the network.
err = notifier(func(client incus.InstanceServer) error {
server, _, err := client.GetServer()
if err != nil {
return err
}
// Clone the network config for this node so we don't modify it and potentially end up sending
// this node's config to another node.
nodeConfig := util.CloneMap(netConfig)
// Merge node specific config items into global config.
maps.Copy(nodeConfig, nodeConfigs[server.Environment.ServerName])
// Create fresh request based on existing network to send to node.
nodeReq := api.NetworksPost{
NetworkPut: api.NetworkPut{
Config: nodeConfig,
Description: n.Description(),
},
Name: n.Name(),
Type: n.Type(),
}
err = client.UseProject(n.Project()).CreateNetwork(nodeReq)
if err != nil {
return err
}
logger.Debug("Created network on cluster member", logger.Ctx{"project": n.Project(), "network": n.Name(), "member": server.Environment.ServerName, "config": nodeReq.Config})
return nil
})
if err != nil {
return err
}
// Mark network global status as networkCreated now that all nodes have succeeded.
err = s.DB.Cluster.Transaction(ctx, func(ctx context.Context, tx *db.ClusterTx) error {
return tx.NetworkCreated(projectName, req.Name)
})
if err != nil {
return err
}
logger.Debug("Marked network global status as created", logger.Ctx{"project": projectName, "network": req.Name})
return nil
}
// Create the network on the system. The clusterNotification flag is used to indicate whether creation request
// is coming from a cluster notification (and if so we should not delete the database record on error).
func doNetworksCreate(ctx context.Context, s *state.State, n network.Network, clientType clusterRequest.ClientType) error {
reverter := revert.New()
defer reverter.Fail()
validateConfig := n.Config()
// Skip the ACLs during validation on cluster join as those aren't yet available in the database.
if clientType == clusterRequest.ClientTypeJoiner {
validateConfig = map[string]string{}
for k, v := range n.Config() {
if k == "security.acls" || strings.HasPrefix(k, "security.acls.") {
continue
}
validateConfig[k] = v
}
}
// Validate so that when run on a cluster node the full config (including node specific config) is checked.
err := n.Validate(validateConfig, clientType)
if err != nil {
return err
}
if n.LocalStatus() == api.NetworkStatusCreated {
logger.Debug("Skipping local network create as already created", logger.Ctx{"project": n.Project(), "network": n.Name()})
return nil
}
// Run initial creation setup for the network driver.
err = n.Create(clientType)
if err != nil {
return err
}
reverter.Add(func() { _ = n.Delete(clientType) })
// Only start networks when not doing a cluster pre-join phase (this ensures that networks are only started
// once the node has fully joined the clustered database and has consistent config with rest of the nodes).
if clientType != clusterRequest.ClientTypeJoiner {
err = n.Start()
if err != nil {
return err
}
}
// Mark local as status as networkCreated.
err = s.DB.Cluster.Transaction(ctx, func(ctx context.Context, tx *db.ClusterTx) error {
return tx.NetworkNodeCreated(n.ID())
})
if err != nil {
return err
}
logger.Debug("Marked network local status as created", logger.Ctx{"project": n.Project(), "network": n.Name()})
reverter.Success()
return nil
}
// swagger:operation GET /1.0/networks/{name} networks network_get
//
// Get the network
//
// Gets a specific network.
//
// ---
// produces:
// - application/json
// parameters:
// - in: query
// name: project
// description: Project name
// type: string
// example: default
// - in: query
// name: target
// description: Cluster member name
// type: string
// example: server01
// responses:
// "200":
// description: Network
// schema:
// type: object
// description: Sync response
// properties:
// type:
// type: string
// description: Response type
// example: sync
// status:
// type: string
// description: Status description
// example: Success
// status_code:
// type: integer
// description: Status code
// example: 200
// metadata:
// $ref: "#/definitions/Network"
// "403":
// $ref: "#/responses/Forbidden"
// "500":
// $ref: "#/responses/InternalServerError"
func networkGet(d *Daemon, r *http.Request) response.Response {
s := d.State()
// If a target was specified, forward the request to the relevant node.
resp := forwardedResponseIfTargetIsRemote(s, r)
if resp != nil {
return resp
}
projectName, reqProject, err := project.NetworkProject(s.DB.Cluster, request.ProjectParam(r))
if err != nil {
return response.SmartError(err)
}
networkName, err := url.PathUnescape(mux.Vars(r)["networkName"])
if err != nil {
return response.SmartError(err)
}
allNodes := false
if s.ServerClustered && request.QueryParam(r, "target") == "" {
allNodes = true
}
n, err := doNetworkGet(s, r, allNodes, projectName, reqProject.Config, networkName)
if err != nil {
return response.SmartError(err)
}
etag := []any{n.Name, n.Managed, n.Type, n.Description, n.Config}
return response.SyncResponseETag(true, &n, etag)
}
// canAccessNetwork checks if the network can be viewed/accessed by the user.
func canAccessNetwork(s *state.State, r *http.Request, projectName string, projectConfig map[string]string, networkName string, managed bool) (bool, error) {
// Don't allow retrieving info about the local server interfaces when not using default project.
if projectName != api.ProjectDefaultName && !managed {
return false, nil
}
// Check for basic access.
if managed {
userHasPermission, err := s.Authorizer.GetPermissionChecker(r.Context(), r, auth.EntitlementCanView, auth.ObjectTypeNetwork)
if err != nil {
return false, err
}
if !userHasPermission(auth.ObjectNetwork(projectName, networkName)) {
return false, nil
}
} else {
userHasResourcesPermission, err := s.Authorizer.GetPermissionChecker(r.Context(), r, auth.EntitlementCanViewResources, auth.ObjectTypeServer)
if err != nil {
return false, err
}
if !userHasResourcesPermission(auth.ObjectServer()) {
return false, nil
}
}
// Check if project allows access to network.
if !project.NetworkAllowed(projectConfig, networkName, managed) {
return false, nil
}
return true, nil
}
// doNetworkGet returns information about the specified network.
// If the network being requested is a managed network and allNodes is true then node specific config is removed.
// Otherwise if allNodes is false then the network's local status is returned.
func doNetworkGet(s *state.State, r *http.Request, allNodes bool, projectName string, reqProjectConfig map[string]string, networkName string) (api.Network, error) {
// Ignore veth pairs (for performance reasons).
if strings.HasPrefix(networkName, "veth") {
return api.Network{}, api.StatusErrorf(http.StatusNotFound, "Network not found")
}
// Get some information.
n, err := network.LoadByName(s, projectName, networkName)
if err != nil && !api.StatusErrorCheck(err, http.StatusNotFound) {
return api.Network{}, fmt.Errorf("Failed loading network: %w", err)
}
// Validate access.
ok, err := canAccessNetwork(s, r, projectName, reqProjectConfig, networkName, n != nil)
if err != nil {
return api.Network{}, err
}
if !ok {
return api.Network{}, api.StatusErrorf(http.StatusNotFound, "Network not found")
}
// Get OS network details.
osInfo, _ := net.InterfaceByName(networkName)
// Quick check.
if osInfo == nil && n == nil {
return api.Network{}, api.StatusErrorf(http.StatusNotFound, "Network not found")
}
// Prepare the response.
apiNet := api.Network{}
apiNet.Name = networkName
apiNet.UsedBy = []string{}
apiNet.Config = map[string]string{}
apiNet.Project = projectName
// Set the device type as needed.
if n != nil {
apiNet.Managed = true
apiNet.Description = n.Description()
apiNet.Type = n.Type()
err = s.Authorizer.CheckPermission(r.Context(), r, auth.ObjectNetwork(projectName, networkName), auth.EntitlementCanEdit)
if err == nil {
// Only allow admins to see network config as sensitive info can be stored there.
apiNet.Config = n.Config()
} else if !api.StatusErrorCheck(err, http.StatusForbidden) {
return api.Network{}, err
}
// If no member is specified, we omit the node-specific fields.
if allNodes {
apiNet.Config = db.StripNodeSpecificNetworkConfig(apiNet.Config)
}
} else if osInfo != nil && int(osInfo.Flags&net.FlagLoopback) > 0 {
apiNet.Type = "loopback"
} else if util.PathExists(fmt.Sprintf("/sys/class/net/%s/bridge", apiNet.Name)) {
apiNet.Type = "bridge"
} else if util.PathExists(fmt.Sprintf("/proc/net/vlan/%s", apiNet.Name)) {
apiNet.Type = "vlan"
} else if util.PathExists(fmt.Sprintf("/sys/class/net/%s/device", apiNet.Name)) {
apiNet.Type = "physical"
} else if util.PathExists(fmt.Sprintf("/sys/class/net/%s/bonding", apiNet.Name)) {
apiNet.Type = "bond"
} else {
vswitch, err := s.OVS()
if err != nil {
return api.Network{}, fmt.Errorf("Failed to connect to OVS: %w", err)
}
_, err = vswitch.GetBridge(context.TODO(), apiNet.Name)
if err == nil {
apiNet.Type = "bridge"
} else {
apiNet.Type = "unknown"
}
}
// Look for instances using the interface.
if apiNet.Type != "loopback" {
var networkID int64
if n != nil {
networkID = n.ID()
}
usedBy, err := network.UsedBy(s, projectName, networkID, apiNet.Name, apiNet.Type, false)
if err != nil {
return api.Network{}, err
}
apiNet.UsedBy = project.FilterUsedBy(s.Authorizer, r, usedBy)
}
if n != nil {
if allNodes {
apiNet.Status = n.Status()
} else {
apiNet.Status = n.LocalStatus()
}
apiNet.Locations = n.Locations()
}
return apiNet, nil
}
// swagger:operation DELETE /1.0/networks/{name} networks network_delete
//
// Delete the network
//
// Removes the network.
//
// ---
// produces:
// - application/json
// parameters:
// - in: query
// name: project
// description: Project name
// type: string
// example: default
// responses:
// "200":
// $ref: "#/responses/EmptySyncResponse"
// "400":
// $ref: "#/responses/BadRequest"
// "403":
// $ref: "#/responses/Forbidden"
// "500":
// $ref: "#/responses/InternalServerError"
func networkDelete(d *Daemon, r *http.Request) response.Response {
s := d.State()
projectName, reqProject, err := project.NetworkProject(s.DB.Cluster, request.ProjectParam(r))
if err != nil {
return response.SmartError(err)
}
networkName, err := url.PathUnescape(mux.Vars(r)["networkName"])
if err != nil {
return response.SmartError(err)
}
// Get the existing network.
n, err := network.LoadByName(s, projectName, networkName)
if err != nil {
return response.SmartError(fmt.Errorf("Failed loading network: %w", err))
}
// Check if project allows access to network.
if !project.NetworkAllowed(reqProject.Config, networkName, n.IsManaged()) {
return response.SmartError(api.StatusErrorf(http.StatusNotFound, "Network not found"))
}
clientType := clusterRequest.UserAgentClientType(r.Header.Get("User-Agent"))
clusterNotification := isClusterNotification(r)
if !clusterNotification {
// Quick checks.
inUse, err := n.IsUsed(false)
if err != nil {
return response.SmartError(err)
}
if inUse {
return response.BadRequest(errors.New("The network is currently in use"))
}
}
if n.LocalStatus() != api.NetworkStatusPending {
err = n.Delete(clientType)
if err != nil {
return response.InternalError(err)
}
}
// If this is a cluster notification, we're done, any database work will be done by the node that is
// originally serving the request.
if clusterNotification {
return response.EmptySyncResponse
}
// If we are clustered, also notify all other nodes, if any.
if s.ServerClustered {
notifier, err := cluster.NewNotifier(s, s.Endpoints.NetworkCert(), s.ServerCert(), cluster.NotifyAll)
if err != nil {
return response.SmartError(err)
}
err = notifier(func(client incus.InstanceServer) error {
return client.UseProject(n.Project()).DeleteNetwork(n.Name())
})
if err != nil {
return response.SmartError(err)
}
}
err = s.DB.Cluster.Transaction(r.Context(), func(ctx context.Context, tx *db.ClusterTx) error {
// Remove the network from the database.
err = tx.DeleteNetwork(ctx, n.Project(), n.Name())
return err
})
if err != nil {
return response.SmartError(err)
}
err = s.Authorizer.DeleteNetwork(r.Context(), projectName, networkName)
if err != nil {
logger.Error("Failed to remove network from authorizer", logger.Ctx{"name": networkName, "project": projectName, "error": err})
}
requestor := request.CreateRequestor(r)
s.Events.SendLifecycle(projectName, lifecycle.NetworkDeleted.Event(n, requestor, nil))
return response.EmptySyncResponse
}
// swagger:operation POST /1.0/networks/{name} networks network_post
//
// Rename the network
//
// Renames an existing network.
//
// ---
// consumes:
// - application/json
// produces:
// - application/json
// parameters:
// - in: query
// name: project
// description: Project name
// type: string
// example: default
// - in: body
// name: network
// description: Network rename request
// required: true
// schema:
// $ref: "#/definitions/NetworkPost"
// responses:
// "200":
// $ref: "#/responses/EmptySyncResponse"
// "400":
// $ref: "#/responses/BadRequest"
// "403":
// $ref: "#/responses/Forbidden"
// "500":
// $ref: "#/responses/InternalServerError"
func networkPost(d *Daemon, r *http.Request) response.Response {
s := d.State()
// FIXME: renaming a network is currently not supported in clustering
// mode. The difficulty is that network.Start() depends on the
// network having already been renamed in the database, which is
// a chicken-and-egg problem for cluster notifications (the
// serving node should typically do the database job, so the
// network is not yet renamed in the db when the notified node
// runs network.Start).
if s.ServerClustered {
return response.BadRequest(errors.New("Renaming clustered network not supported"))
}
projectName, reqProject, err := project.NetworkProject(s.DB.Cluster, request.ProjectParam(r))
if err != nil {
return response.SmartError(err)
}
networkName, err := url.PathUnescape(mux.Vars(r)["networkName"])
if err != nil {
return response.SmartError(err)
}
req := api.NetworkPost{}
// Parse the request.
err = json.NewDecoder(r.Body).Decode(&req)
if err != nil {
return response.BadRequest(err)
}
// Get the existing network.
n, err := network.LoadByName(s, projectName, networkName)
if err != nil {
return response.SmartError(fmt.Errorf("Failed loading network: %w", err))
}
// Check if project allows access to network.
if !project.NetworkAllowed(reqProject.Config, networkName, n.IsManaged()) {
return response.SmartError(api.StatusErrorf(http.StatusNotFound, "Network not found"))
}
if n.Status() != api.NetworkStatusCreated {
return response.BadRequest(errors.New("Cannot rename network when not in created state"))
}
// Ensure new name is supplied.
if req.Name == "" {
return response.BadRequest(errors.New("New network name not provided"))
}
// Perform generic name validation.
err = validate.IsAPIName(req.Name, false)
if err != nil {
return response.BadRequest(fmt.Errorf("Invalid network name: %w", err))
}
// Perform driver-specific name validation.
err = n.ValidateName(req.Name)
if err != nil {
return response.BadRequest(fmt.Errorf("Invalid network name: %w", err))
}
// Check network isn't in use.
inUse, err := n.IsUsed(false)
if err != nil {
return response.InternalError(fmt.Errorf("Failed checking network in use: %w", err))
}
if inUse {
return response.BadRequest(errors.New("Network is currently in use"))
}
var networks []string
err = s.DB.Cluster.Transaction(r.Context(), func(ctx context.Context, tx *db.ClusterTx) error {
// Check that the name isn't already in used by an existing managed network.
networks, err = tx.GetNetworks(ctx, projectName)
return err
})
if err != nil {
return response.InternalError(err)
}
if slices.Contains(networks, req.Name) {
return response.Conflict(fmt.Errorf("Network %q already exists", req.Name))
}
// Rename it.
err = n.Rename(req.Name)
if err != nil {
return response.SmartError(err)
}
err = s.Authorizer.RenameNetwork(r.Context(), projectName, networkName, req.Name)
if err != nil {
logger.Error("Failed to rename network in authorizer", logger.Ctx{"old_name": networkName, "new_name": req.Name, "project": projectName, "error": err})
}
requestor := request.CreateRequestor(r)
lc := lifecycle.NetworkRenamed.Event(n, requestor, map[string]any{"old_name": networkName})
s.Events.SendLifecycle(projectName, lc)
return response.SyncResponseLocation(true, nil, lc.Source)
}
// swagger:operation PUT /1.0/networks/{name} networks network_put
//
// Update the network
//
// Updates the entire network configuration.
//
// ---
// consumes:
// - application/json
// produces:
// - application/json
// parameters:
// - in: query
// name: project
// description: Project name
// type: string
// example: default
// - in: query
// name: target
// description: Cluster member name
// type: string
// example: server01
// - in: body
// name: network
// description: Network configuration
// required: true
// schema:
// $ref: "#/definitions/NetworkPut"
// responses:
// "200":
// $ref: "#/responses/EmptySyncResponse"
// "400":
// $ref: "#/responses/BadRequest"
// "403":
// $ref: "#/responses/Forbidden"
// "412":
// $ref: "#/responses/PreconditionFailed"
// "500":
// $ref: "#/responses/InternalServerError"
func networkPut(d *Daemon, r *http.Request) response.Response {
s := d.State()
// If a target was specified, forward the request to the relevant node.
resp := forwardedResponseIfTargetIsRemote(s, r)
if resp != nil {
return resp
}
projectName, reqProject, err := project.NetworkProject(s.DB.Cluster, request.ProjectParam(r))
if err != nil {
return response.SmartError(err)
}
networkName, err := url.PathUnescape(mux.Vars(r)["networkName"])
if err != nil {
return response.SmartError(err)
}
// Get the existing network.
n, err := network.LoadByName(s, projectName, networkName)
if err != nil {
return response.SmartError(fmt.Errorf("Failed loading network: %w", err))
}
// Check if project allows access to network.
if !project.NetworkAllowed(reqProject.Config, networkName, n.IsManaged()) {
return response.SmartError(api.StatusErrorf(http.StatusNotFound, "Network not found"))
}
targetNode := request.QueryParam(r, "target")
if targetNode == "" && n.Status() != api.NetworkStatusCreated {
return response.BadRequest(errors.New("Cannot update network global config when not in created state"))
}
// Duplicate config for etag modification and generation.
etagConfig := localUtil.CopyConfig(n.Config())
// If no target node is specified and the daemon is clustered, we omit the node-specific fields so that
// the e-tag can be generated correctly. This is because the GET request used to populate the request
// will also remove node-specific keys when no target is specified.
if targetNode == "" && s.ServerClustered {
etagConfig = db.StripNodeSpecificNetworkConfig(etagConfig)
}
// Validate the ETag.
etag := []any{n.Name(), n.IsManaged(), n.Type(), n.Description(), etagConfig}
err = localUtil.EtagCheck(r, etag)
if err != nil {
return response.PreconditionFailed(err)
}
// Decode the request.
req := api.NetworkPut{}
err = json.NewDecoder(r.Body).Decode(&req)
if err != nil {
return response.BadRequest(err)
}
// In clustered mode, we differentiate between node specific and non-node specific config keys based on
// whether the user has specified a target to apply the config to.
if s.ServerClustered {
curConfig := n.Config()
changedConfig := make(map[string]string, len(req.Config))
for key, value := range req.Config {
if curConfig[key] == value {
continue
}
changedConfig[key] = value
}
if targetNode == "" {
// If no target is specified, then ensure only non-node-specific config keys are changed.
for k := range changedConfig {
if db.IsNodeSpecificNetworkConfig(k) {
return response.BadRequest(fmt.Errorf("Config key %q is cluster member specific", k))
}
}
} else {
// If a target is specified, then ensure only node-specific config keys are changed.
for k := range changedConfig {
if !db.IsNodeSpecificNetworkConfig(k) {
return response.BadRequest(fmt.Errorf("Config key %q may not be used as member-specific key", k))
}
}
}
}
clientType := clusterRequest.UserAgentClientType(r.Header.Get("User-Agent"))
resp = doNetworkUpdate(n, req, targetNode, clientType, r.Method, s.ServerClustered)
requestor := request.CreateRequestor(r)
s.Events.SendLifecycle(projectName, lifecycle.NetworkUpdated.Event(n, requestor, nil))
return resp
}
// swagger:operation PATCH /1.0/networks/{name} networks network_patch
//
// Partially update the network
//
// Updates a subset of the network configuration.
//
// ---
// consumes:
// - application/json
// produces:
// - application/json
// parameters:
// - in: query
// name: project
// description: Project name
// type: string
// example: default
// - in: query
// name: target
// description: Cluster member name
// type: string
// example: server01
// - in: body
// name: network
// description: Network configuration
// required: true
// schema:
// $ref: "#/definitions/NetworkPut"
// responses:
// "200":
// $ref: "#/responses/EmptySyncResponse"
// "400":
// $ref: "#/responses/BadRequest"
// "403":
// $ref: "#/responses/Forbidden"
// "412":
// $ref: "#/responses/PreconditionFailed"
// "500":
// $ref: "#/responses/InternalServerError"
func networkPatch(d *Daemon, r *http.Request) response.Response {
return networkPut(d, r)
}
// doNetworkUpdate loads the current local network config, merges with the requested network config, validates
// and applies the changes. Will also notify other cluster nodes of non-node specific config if needed.
func doNetworkUpdate(n network.Network, req api.NetworkPut, targetNode string, clientType clusterRequest.ClientType, httpMethod string, clustered bool) response.Response {
if req.Config == nil {
req.Config = map[string]string{}
}
// Normally a "put" request will replace all existing config, however when clustered, we need to account
// for the node specific config keys and not replace them when the request doesn't specify a specific node.
if targetNode == "" && httpMethod != http.MethodPatch && clustered {
// If non-node specific config being updated via "put" method in cluster, then merge the current
// node-specific network config with the submitted config to allow validation.
// This allows removal of non-node specific keys when they are absent from request config.
for k, v := range n.Config() {
if db.IsNodeSpecificNetworkConfig(k) {
req.Config[k] = v
}
}
} else if httpMethod == http.MethodPatch {
// If config being updated via "patch" method, then merge all existing config with the keys that
// are present in the request config.
for k, v := range n.Config() {
_, ok := req.Config[k]
if !ok {
req.Config[k] = v
}
}
}
// Validate the merged configuration.
err := n.Validate(req.Config, clientType)
if err != nil {
return response.BadRequest(err)
}
// Apply the new configuration (will also notify other cluster nodes if needed).
err = n.Update(req, targetNode, clientType)
if err != nil {
return response.SmartError(err)
}
return response.EmptySyncResponse
}
// swagger:operation GET /1.0/networks/{name}/leases networks networks_leases_get
//
// Get the DHCP leases
//
// Returns a list of DHCP leases for the network.
//
// ---
// produces:
// - application/json
// parameters:
// - in: query
// name: project
// description: Project name
// type: string
// example: default
// - in: query
// name: target
// description: Cluster member name
// type: string
// example: server01
// responses:
// "200":
// description: API endpoints
// schema:
// type: object
// description: Sync response
// properties:
// type:
// type: string
// description: Response type
// example: sync
// status:
// type: string
// description: Status description
// example: Success
// status_code:
// type: integer
// description: Status code
// example: 200
// metadata:
// type: array
// description: List of DHCP leases
// items:
// $ref: "#/definitions/NetworkLease"
// "403":
// $ref: "#/responses/Forbidden"
// "500":
// $ref: "#/responses/InternalServerError"
func networkLeasesGet(d *Daemon, r *http.Request) response.Response {
s := d.State()
projectName, reqProject, err := project.NetworkProject(s.DB.Cluster, request.ProjectParam(r))
if err != nil {
return response.SmartError(err)
}
networkName, err := url.PathUnescape(mux.Vars(r)["networkName"])
if err != nil {
return response.SmartError(err)
}
// Attempt to load the network.
n, err := network.LoadByName(s, projectName, networkName)
if err != nil {
return response.SmartError(fmt.Errorf("Failed loading network: %w", err))
}
// Check if project allows access to network.
if !project.NetworkAllowed(reqProject.Config, networkName, n.IsManaged()) {
return response.SmartError(api.StatusErrorf(http.StatusNotFound, "Network not found"))
}
clientType := clusterRequest.UserAgentClientType(r.Header.Get("User-Agent"))
leases, err := n.Leases(reqProject.Name, clientType)
if err != nil {
return response.SmartError(err)
}
return response.SyncResponse(true, leases)
}
func networkStartup(s *state.State) error {
var err error
// Get a list of projects.
var projectNames []string
err = s.DB.Cluster.Transaction(s.ShutdownCtx, func(ctx context.Context, tx *db.ClusterTx) error {
projectNames, err = dbCluster.GetProjectNames(ctx, tx.Tx())
return err
})
if err != nil {
return fmt.Errorf("Failed to load projects: %w", err)
}
// Build a list of networks to initialize, keyed by project and network name.
const networkPriorityStandalone = 0 // Start networks not dependent on any other network first.
const networkPriorityPhysical = 1 // Start networks dependent on physical interfaces second.
const networkPriorityLogical = 2 // Start networks dependent logical networks third.
initNetworks := []map[network.ProjectNetwork]struct{}{
networkPriorityStandalone: make(map[network.ProjectNetwork]struct{}),
networkPriorityPhysical: make(map[network.ProjectNetwork]struct{}),
networkPriorityLogical: make(map[network.ProjectNetwork]struct{}),
}
err = s.DB.Cluster.Transaction(s.ShutdownCtx, func(ctx context.Context, tx *db.ClusterTx) error {
for _, projectName := range projectNames {
networkNames, err := tx.GetCreatedNetworkNamesByProject(ctx, projectName)
if err != nil {
return fmt.Errorf("Failed to load networks for project %q: %w", projectName, err)
}
for _, networkName := range networkNames {
pn := network.ProjectNetwork{
ProjectName: projectName,
NetworkName: networkName,
}
// Assume all networks are networkPriorityStandalone initially.
initNetworks[networkPriorityStandalone][pn] = struct{}{}
}
}
return nil
})
if err != nil {
return err
}
loadedNetworks := make(map[network.ProjectNetwork]network.Network)
initNetwork := func(n network.Network, priority int) error {
err = n.Start()
if err != nil {
err = fmt.Errorf("Failed starting: %w", err)
_ = s.DB.Cluster.Transaction(s.ShutdownCtx, func(ctx context.Context, tx *db.ClusterTx) error {
return tx.UpsertWarningLocalNode(ctx, n.Project(), dbCluster.TypeNetwork, int(n.ID()), warningtype.NetworkUnvailable, err.Error())
})
return err
}
logger.Info("Initialized network", logger.Ctx{"project": n.Project(), "name": n.Name()})
// Network initialized successfully so remove it from the list so its not retried.
pn := network.ProjectNetwork{
ProjectName: n.Project(),
NetworkName: n.Name(),
}
delete(initNetworks[priority], pn)
_ = warnings.ResolveWarningsByLocalNodeAndProjectAndTypeAndEntity(s.DB.Cluster, n.Project(), warningtype.NetworkUnvailable, dbCluster.TypeNetwork, int(n.ID()))
return nil
}
loadAndInitNetwork := func(pn network.ProjectNetwork, priority int, firstPass bool) error {
var err error
var n network.Network
if firstPass && loadedNetworks[pn] != nil {
// Check if network already loaded from during first pass phase.
n = loadedNetworks[pn]
} else {
n, err = network.LoadByName(s, pn.ProjectName, pn.NetworkName)
if err != nil {
if api.StatusErrorCheck(err, http.StatusNotFound) {
// Network has been deleted since we began trying to start it so delete
// entry.
delete(initNetworks[priority], pn)
return nil
}
return fmt.Errorf("Failed loading: %w", err)
}
}
netConfig := n.Config()
err = n.Validate(netConfig, clusterRequest.ClientTypeNormal)
if err != nil {
return fmt.Errorf("Failed validating: %w", err)
}
// Update network start priority based on dependencies.
if netConfig["parent"] != "" && priority != networkPriorityPhysical {
// Start networks that depend on physical interfaces existing after
// non-dependent networks.
delete(initNetworks[priority], pn)
initNetworks[networkPriorityPhysical][pn] = struct{}{}
return nil
} else if netConfig["network"] != "" && priority != networkPriorityLogical {
// Start networks that depend on other logical networks after networks after
// non-dependent networks and networks that depend on physical interfaces.
delete(initNetworks[priority], pn)
initNetworks[networkPriorityLogical][pn] = struct{}{}
return nil
}
err = initNetwork(n, priority)
if err != nil {
return err
}
return nil
}
// Try initializing networks in priority order.
for priority := range initNetworks {
for pn := range initNetworks[priority] {
err := loadAndInitNetwork(pn, priority, true)
if err != nil {
logger.Error("Failed initializing network", logger.Ctx{"project": pn.ProjectName, "network": pn.NetworkName, "err": err})
continue
}
}
}
loadedNetworks = nil // Don't store loaded networks after first pass.
remainingNetworks := 0
for _, networks := range initNetworks {
remainingNetworks += len(networks)
}
// For any remaining networks that were not successfully initialized, we now start a go routine to
// periodically try to initialize them again in the background.
if remainingNetworks > 0 {
go func() {
for {
t := time.NewTimer(time.Duration(time.Minute))
select {
case <-s.ShutdownCtx.Done():
t.Stop()
return
case <-t.C:
t.Stop()
tryInstancesStart := false
// Try initializing networks in priority order.
for priority := range initNetworks {
for pn := range initNetworks[priority] {
err := loadAndInitNetwork(pn, priority, false)
if err != nil {
logger.Error("Failed initializing network", logger.Ctx{"project": pn.ProjectName, "network": pn.NetworkName, "err": err})
continue
}
tryInstancesStart = true // We initialized at least one network.
}
}
remainingNetworks := 0
for _, networks := range initNetworks {
remainingNetworks += len(networks)
}
if remainingNetworks <= 0 {
logger.Info("All networks initialized")
}
// At least one remaining network was initialized, check if any instances
// can now start.
if tryInstancesStart {
instances, err := instance.LoadNodeAll(s, instancetype.Any)
if err != nil {
logger.Warn("Failed loading instances to start", logger.Ctx{"err": err})
} else {
instancesStart(s, instances)
}
}
if remainingNetworks <= 0 {
return // Our job here is done.
}
}
}
}()
} else {
logger.Info("All networks initialized")
}
return nil
}
func networkShutdown(s *state.State) {
var err error
// Get a list of projects.
var projectNames []string
err = s.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
projectNames, err = dbCluster.GetProjectNames(ctx, tx.Tx())
return err
})
if err != nil {
logger.Error("Failed shutting down networks, couldn't load projects", logger.Ctx{"err": err})
return
}
for _, projectName := range projectNames {
var networks []string
err := s.DB.Cluster.Transaction(context.TODO(), func(ctx context.Context, tx *db.ClusterTx) error {
// Get a list of managed networks.
networks, err = tx.GetNetworks(ctx, projectName)
return err
})
if err != nil {
logger.Error("Failed shutting down networks, couldn't load networks for project", logger.Ctx{"project": projectName, "err": err})
continue
}
// Bring them all down.
for _, name := range networks {
n, err := network.LoadByName(s, projectName, name)
if err != nil {
logger.Error("Failed shutting down network, couldn't load network", logger.Ctx{"network": name, "project": projectName, "err": err})
continue
}
err = n.Stop()
if err != nil {
logger.Error("Failed to bring down network", logger.Ctx{"err": err, "project": projectName, "name": name})
}
}
}
}
// networkRestartOVN is used to trigger a restart of all OVN networks.
func networkRestartOVN(s *state.State) error {
logger.Infof("Restarting OVN networks")
// Get a list of projects.
var projectNames []string
var err error
err = s.DB.Cluster.Transaction(s.ShutdownCtx, func(ctx context.Context, tx *db.ClusterTx) error {
projectNames, err = dbCluster.GetProjectNames(ctx, tx.Tx())
return err
})
if err != nil {
return fmt.Errorf("Failed to load projects: %w", err)
}
// Go over all the networks in every project.
for _, projectName := range projectNames {
var networkNames []string
err := s.DB.Cluster.Transaction(s.ShutdownCtx, func(ctx context.Context, tx *db.ClusterTx) error {
networkNames, err = tx.GetCreatedNetworkNamesByProject(ctx, projectName)
return err
})
if err != nil {
return fmt.Errorf("Failed to load networks for project %q: %w", projectName, err)
}
for _, networkName := range networkNames {
// Load the network struct.
n, err := network.LoadByName(s, projectName, networkName)
if err != nil {
return fmt.Errorf("Failed to load network %q in project %q: %w", networkName, projectName, err)
}
// Skip non-OVN networks.
if n.DBType() != db.NetworkTypeOVN {
continue
}
// Restart the network.
err = n.Start()
if err != nil {
return fmt.Errorf("Failed to restart network %q in project %q: %w", networkName, projectName, err)
}
}
}
return nil
}
// swagger:operation GET /1.0/networks/{name}/state networks networks_state_get
//
// Get the network state
//
// Returns the current network state information.
//
// ---
// produces:
// - application/json
// parameters:
// - in: query
// name: project
// description: Project name
// type: string
// example: default
// - in: query
// name: target
// description: Cluster member name
// type: string
// example: server01
// responses:
// "200":
// description: API endpoints
// schema:
// type: object
// description: Sync response
// properties:
// type:
// type: string
// description: Response type
// example: sync
// status:
// type: string
// description: Status description
// example: Success
// status_code:
// type: integer
// description: Status code
// example: 200
// metadata:
// $ref: "#/definitions/NetworkState"
// "403":
// $ref: "#/responses/Forbidden"
// "500":
// $ref: "#/responses/InternalServerError"
func networkStateGet(d *Daemon, r *http.Request) response.Response {
s := d.State()
// If a target was specified, forward the request to the relevant node.
resp := forwardedResponseIfTargetIsRemote(s, r)
if resp != nil {
return resp
}
projectName, reqProject, err := project.NetworkProject(s.DB.Cluster, request.ProjectParam(r))
if err != nil {
return response.SmartError(err)
}
networkName, err := url.PathUnescape(mux.Vars(r)["networkName"])
if err != nil {
return response.SmartError(err)
}
n, err := network.LoadByName(s, projectName, networkName)
if err != nil && !api.StatusErrorCheck(err, http.StatusNotFound) {
return response.SmartError(fmt.Errorf("Failed loading network: %w", err))
}
// Check if project allows access to network.
if !project.NetworkAllowed(reqProject.Config, networkName, n != nil && n.IsManaged()) {
return response.SmartError(api.StatusErrorf(http.StatusNotFound, "Network not found"))
}
var state *api.NetworkState
if n != nil {
state, err = n.State()
if err != nil {
return response.SmartError(err)
}
} else {
state, err = resources.GetNetworkState(networkName)
if err != nil {
return response.SmartError(err)
}
}
return response.SyncResponse(true, state)
}
|