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
|
//go:build !remote
package libpod
import (
"database/sql"
"errors"
"fmt"
"os"
"path/filepath"
goruntime "runtime"
"strings"
"time"
"github.com/containers/common/libnetwork/types"
"github.com/containers/podman/v5/libpod/define"
"github.com/containers/storage"
"github.com/sirupsen/logrus"
// SQLite backend for database/sql
_ "github.com/mattn/go-sqlite3"
)
const schemaVersion = 1
// SQLiteState is a state implementation backed by a SQLite database
type SQLiteState struct {
valid bool
conn *sql.DB
runtime *Runtime
}
const (
// Deal with timezone automatically.
sqliteOptionLocation = "_loc=auto"
// Force an fsync after each transaction (https://www.sqlite.org/pragma.html#pragma_synchronous).
sqliteOptionSynchronous = "&_sync=FULL"
// Allow foreign keys (https://www.sqlite.org/pragma.html#pragma_foreign_keys).
sqliteOptionForeignKeys = "&_foreign_keys=1"
// Make sure that transactions happen exclusively.
sqliteOptionTXLock = "&_txlock=exclusive"
// Assembled sqlite options used when opening the database.
sqliteOptions = "db.sql?" +
sqliteOptionLocation +
sqliteOptionSynchronous +
sqliteOptionForeignKeys +
sqliteOptionTXLock
)
// NewSqliteState creates a new SQLite-backed state database.
func NewSqliteState(runtime *Runtime) (_ State, defErr error) {
logrus.Info("Using sqlite as database backend")
state := new(SQLiteState)
basePath := runtime.storageConfig.GraphRoot
if runtime.storageConfig.TransientStore {
basePath = runtime.storageConfig.RunRoot
} else if !runtime.storageSet.StaticDirSet {
basePath = runtime.config.Engine.StaticDir
}
// c/storage is set up *after* the DB - so even though we use the c/s
// root (or, for transient, runroot) dir, we need to make the dir
// ourselves.
if err := os.MkdirAll(basePath, 0700); err != nil {
return nil, fmt.Errorf("creating root directory: %w", err)
}
// Make sure busy timeout is set to high value to keep retrying when the db is locked.
// Timeout is in ms, so set it to 100s to have enough time to retry the operations.
// Some users might want to experiment with different timeout values (#23236)
// DO NOT DOCUMENT or recommend PODMAN_SQLITE_BUSY_TIMEOUT outside of testing.
busyTimeout := "100000"
if env, ok := os.LookupEnv("PODMAN_SQLITE_BUSY_TIMEOUT"); ok {
logrus.Debugf("PODMAN_SQLITE_BUSY_TIMEOUT is set to %s", env)
busyTimeout = env
}
sqliteOptionBusyTimeout := "&_busy_timeout=" + busyTimeout
conn, err := sql.Open("sqlite3", filepath.Join(basePath, sqliteOptions+sqliteOptionBusyTimeout))
if err != nil {
return nil, fmt.Errorf("initializing sqlite database: %w", err)
}
defer func() {
if defErr != nil {
if err := conn.Close(); err != nil {
logrus.Errorf("Error closing SQLite DB connection: %v", err)
}
}
}()
if err := initSQLiteDB(conn); err != nil {
return nil, err
}
state.conn = conn
state.valid = true
state.runtime = runtime
return state, nil
}
// Close closes the state and prevents further use
func (s *SQLiteState) Close() error {
if err := s.conn.Close(); err != nil {
return err
}
s.valid = false
return nil
}
// Refresh clears container and pod states after a reboot
func (s *SQLiteState) Refresh() (defErr error) {
if !s.valid {
return define.ErrDBClosed
}
// Retrieve all containers, pods, and volumes.
// Maps are indexed by ID (or volume name) so we know which goes where,
// and store the marshalled state JSON
ctrStates := make(map[string]string)
podStates := make(map[string]string)
volumeStates := make(map[string]string)
ctrRows, err := s.conn.Query("SELECT ID, JSON FROM ContainerState;")
if err != nil {
return fmt.Errorf("querying for container states: %w", err)
}
defer ctrRows.Close()
for ctrRows.Next() {
var (
id, stateJSON string
)
if err := ctrRows.Scan(&id, &stateJSON); err != nil {
return fmt.Errorf("scanning container state row: %w", err)
}
ctrState := new(ContainerState)
if err := json.Unmarshal([]byte(stateJSON), ctrState); err != nil {
return fmt.Errorf("unmarshalling container state json: %w", err)
}
// Refresh the state
resetContainerState(ctrState)
newJSON, err := json.Marshal(ctrState)
if err != nil {
return fmt.Errorf("marshalling container state json: %w", err)
}
ctrStates[id] = string(newJSON)
}
if err := ctrRows.Err(); err != nil {
return err
}
podRows, err := s.conn.Query("SELECT ID, JSON FROM PodState;")
if err != nil {
return fmt.Errorf("querying for pod states: %w", err)
}
defer podRows.Close()
for podRows.Next() {
var (
id, stateJSON string
)
if err := podRows.Scan(&id, &stateJSON); err != nil {
return fmt.Errorf("scanning pod state row: %w", err)
}
podState := new(podState)
if err := json.Unmarshal([]byte(stateJSON), podState); err != nil {
return fmt.Errorf("unmarshalling pod state json: %w", err)
}
// Refresh the state
resetPodState(podState)
newJSON, err := json.Marshal(podState)
if err != nil {
return fmt.Errorf("marshalling pod state json: %w", err)
}
podStates[id] = string(newJSON)
}
if err := podRows.Err(); err != nil {
return err
}
volRows, err := s.conn.Query("SELECT Name, JSON FROM VolumeState;")
if err != nil {
return fmt.Errorf("querying for volume states: %w", err)
}
defer volRows.Close()
for volRows.Next() {
var (
name, stateJSON string
)
if err := volRows.Scan(&name, &stateJSON); err != nil {
return fmt.Errorf("scanning volume state row: %w", err)
}
volState := new(VolumeState)
if err := json.Unmarshal([]byte(stateJSON), volState); err != nil {
return fmt.Errorf("unmarshalling volume state json: %w", err)
}
// Refresh the state
resetVolumeState(volState)
newJSON, err := json.Marshal(volState)
if err != nil {
return fmt.Errorf("marshalling volume state json: %w", err)
}
volumeStates[name] = string(newJSON)
}
if err := volRows.Err(); err != nil {
return err
}
// Write updated states back to DB, and perform additional maintenance
// (Remove exit codes and exec sessions)
tx, err := s.conn.Begin()
if err != nil {
return fmt.Errorf("beginning refresh transaction: %w", err)
}
defer func() {
if defErr != nil {
if err := tx.Rollback(); err != nil {
logrus.Errorf("Rolling back transaction to refresh database state: %v", err)
}
}
}()
for id, json := range ctrStates {
if _, err := tx.Exec("UPDATE ContainerState SET JSON=? WHERE ID=?;", json, id); err != nil {
return fmt.Errorf("updating container state: %w", err)
}
}
for id, json := range podStates {
if _, err := tx.Exec("UPDATE PodState SET JSON=? WHERE ID=?;", json, id); err != nil {
return fmt.Errorf("updating pod state: %w", err)
}
}
for name, json := range volumeStates {
if _, err := tx.Exec("UPDATE VolumeState SET JSON=? WHERE Name=?;", json, name); err != nil {
return fmt.Errorf("updating volume state: %w", err)
}
}
if _, err := tx.Exec("DELETE FROM ContainerExitCode;"); err != nil {
return fmt.Errorf("removing container exit codes: %w", err)
}
if _, err := tx.Exec("DELETE FROM ContainerExecSession;"); err != nil {
return fmt.Errorf("removing container exec sessions: %w", err)
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("committing transaction: %w", err)
}
return nil
}
// GetDBConfig retrieves runtime configuration fields that were created when
// the database was first initialized
func (s *SQLiteState) GetDBConfig() (*DBConfig, error) {
if !s.valid {
return nil, define.ErrDBClosed
}
cfg := new(DBConfig)
var staticDir, tmpDir, graphRoot, runRoot, graphDriver, volumeDir string
row := s.conn.QueryRow("SELECT StaticDir, TmpDir, GraphRoot, RunRoot, GraphDriver, VolumeDir FROM DBConfig;")
if err := row.Scan(&staticDir, &tmpDir, &graphRoot, &runRoot, &graphDriver, &volumeDir); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return cfg, nil
}
return nil, fmt.Errorf("retrieving DB config: %w", err)
}
cfg.LibpodRoot = staticDir
cfg.LibpodTmp = tmpDir
cfg.StorageRoot = graphRoot
cfg.StorageTmp = runRoot
cfg.GraphDriver = graphDriver
cfg.VolumePath = volumeDir
return cfg, nil
}
// ValidateDBConfig validates paths in the given runtime against the database
func (s *SQLiteState) ValidateDBConfig(runtime *Runtime) (defErr error) {
if !s.valid {
return define.ErrDBClosed
}
storeOpts, err := storage.DefaultStoreOptions()
if err != nil {
return err
}
const createRow = `
INSERT INTO DBconfig VALUES (
?, ?, ?,
?, ?, ?,
?, ?, ?
);`
var (
dbOS, staticDir, tmpDir, graphRoot, runRoot, graphDriver, volumePath string
runtimeOS = goruntime.GOOS
runtimeStaticDir = filepath.Clean(s.runtime.config.Engine.StaticDir)
runtimeTmpDir = filepath.Clean(s.runtime.config.Engine.TmpDir)
runtimeGraphRoot = filepath.Clean(s.runtime.StorageConfig().GraphRoot)
runtimeRunRoot = filepath.Clean(s.runtime.StorageConfig().RunRoot)
runtimeGraphDriver = s.runtime.StorageConfig().GraphDriverName
runtimeVolumePath = filepath.Clean(s.runtime.config.Engine.VolumePath)
)
// Some fields may be empty, indicating they are set to the default.
// If so, grab the default from c/storage for them.
if runtimeGraphRoot == "" {
runtimeGraphRoot = storeOpts.GraphRoot
}
if runtimeRunRoot == "" {
runtimeRunRoot = storeOpts.RunRoot
}
if runtimeGraphDriver == "" {
runtimeGraphDriver = storeOpts.GraphDriverName
}
// We have to do this in a transaction to ensure mutual exclusion.
// Otherwise we have a race - multiple processes can be checking the
// row's existence simultaneously, both try to create it, second one to
// get the transaction lock gets an error.
// TODO: The transaction isn't strictly necessary, and there's a (small)
// chance it's a perf hit. If it is, we can move it entirely within the
// `errors.Is()` block below, with extra validation to ensure the row
// still does not exist (and, if it does, to retry this function).
tx, err := s.conn.Begin()
if err != nil {
return fmt.Errorf("beginning database validation transaction: %w", err)
}
defer func() {
if defErr != nil {
if err := tx.Rollback(); err != nil {
logrus.Errorf("Rolling back transaction to validate database: %v", err)
}
}
}()
row := tx.QueryRow("SELECT Os, StaticDir, TmpDir, GraphRoot, RunRoot, GraphDriver, VolumeDir FROM DBConfig;")
if err := row.Scan(&dbOS, &staticDir, &tmpDir, &graphRoot, &runRoot, &graphDriver, &volumePath); err != nil {
if errors.Is(err, sql.ErrNoRows) {
if _, err := tx.Exec(createRow, 1, schemaVersion, runtimeOS,
runtimeStaticDir, runtimeTmpDir, runtimeGraphRoot,
runtimeRunRoot, runtimeGraphDriver, runtimeVolumePath); err != nil {
return fmt.Errorf("adding DB config row: %w", err)
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("committing write of database validation row: %w", err)
}
return nil
}
return fmt.Errorf("retrieving DB config: %w", err)
}
// Sometimes, for as-yet unclear reasons, the database value ends up set
// to the empty string. If it does, this evaluation is always going to
// fail, and libpod will be unusable.
// At this point, the check is effectively meaningless - we don't
// actually know the settings we should be checking against. The best
// thing we can do (and what BoltDB did in this case) is to compare
// against the default, on the assumption that is what was in use.
// TODO: We can't remove this code without breaking existing SQLite DBs
// that already have incorrect values in the database, but we should
// investigate why this is happening and try and prevent the creation of
// new databases with these garbage checks.
if graphRoot == "" {
logrus.Debugf("Database uses empty-string graph root, substituting default %q", storeOpts.GraphRoot)
graphRoot = storeOpts.GraphRoot
}
if runRoot == "" {
logrus.Debugf("Database uses empty-string run root, substituting default %q", storeOpts.RunRoot)
runRoot = storeOpts.RunRoot
}
if graphDriver == "" {
logrus.Debugf("Database uses empty-string graph driver, substituting default %q", storeOpts.GraphDriverName)
graphDriver = storeOpts.GraphDriverName
}
checkField := func(fieldName, dbVal, ourVal string, isPath bool) error {
if isPath {
// Tolerate symlinks when possible - most relevant for OStree systems
// and rootless containers, where we want to put containers in /home,
// which is symlinked to /var/home.
// Ignore ENOENT as reasonable, as some paths may not exist in early Libpod
// init.
if dbVal != "" {
checkedVal, err := evalSymlinksIfExists(dbVal)
if err != nil {
return fmt.Errorf("cannot evaluate symlinks on DB %s path %q: %w", fieldName, dbVal, err)
}
dbVal = checkedVal
}
if ourVal != "" {
checkedVal, err := evalSymlinksIfExists(ourVal)
if err != nil {
return fmt.Errorf("cannot evaluate symlinks on our %s path %q: %w", fieldName, ourVal, err)
}
ourVal = checkedVal
}
}
if dbVal != ourVal {
return fmt.Errorf("database %s %q does not match our %s %q: %w", fieldName, dbVal, fieldName, ourVal, define.ErrDBBadConfig)
}
return nil
}
if err := checkField("os", dbOS, runtimeOS, false); err != nil {
return err
}
if err := checkField("static dir", staticDir, runtimeStaticDir, true); err != nil {
return err
}
if err := checkField("tmp dir", tmpDir, runtimeTmpDir, true); err != nil {
return err
}
if err := checkField("graph root", graphRoot, runtimeGraphRoot, true); err != nil {
return err
}
if err := checkField("run root", runRoot, runtimeRunRoot, true); err != nil {
return err
}
if err := checkField("graph driver", graphDriver, runtimeGraphDriver, false); err != nil {
return err
}
if err := checkField("volume path", volumePath, runtimeVolumePath, true); err != nil {
return err
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("committing database validation row: %w", err)
}
// Do not return any error after the commit call because the defer will
// try to roll back the transaction which results in an logged error.
return nil
}
// GetContainerName returns the name of the container associated with a given
// ID. Returns ErrNoSuchCtr if the ID does not exist.
func (s *SQLiteState) GetContainerName(id string) (string, error) {
if id == "" {
return "", define.ErrEmptyID
}
if !s.valid {
return "", define.ErrDBClosed
}
var name string
row := s.conn.QueryRow("SELECT Name FROM ContainerConfig WHERE ID=?;", id)
if err := row.Scan(&name); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return "", define.ErrNoSuchCtr
}
return "", fmt.Errorf("looking up container %s name: %w", id, err)
}
return name, nil
}
// GetPodName returns the name of the pod associated with a given ID.
// Returns ErrNoSuchPod if the ID does not exist.
func (s *SQLiteState) GetPodName(id string) (string, error) {
if id == "" {
return "", define.ErrEmptyID
}
if !s.valid {
return "", define.ErrDBClosed
}
var name string
row := s.conn.QueryRow("SELECT Name FROM PodConfig WHERE ID=?;", id)
if err := row.Scan(&name); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return "", define.ErrNoSuchPod
}
return "", fmt.Errorf("looking up pod %s name: %w", id, err)
}
return name, nil
}
// Container retrieves a single container from the state by its full ID
func (s *SQLiteState) Container(id string) (*Container, error) {
if id == "" {
return nil, define.ErrEmptyID
}
if !s.valid {
return nil, define.ErrDBClosed
}
ctrConfig, err := s.getCtrConfig(id)
if err != nil {
return nil, err
}
ctr := new(Container)
ctr.config = ctrConfig
ctr.state = new(ContainerState)
ctr.runtime = s.runtime
if err := finalizeCtrSqlite(ctr); err != nil {
return nil, err
}
return ctr, nil
}
// LookupContainerID retrieves a container ID from the state by full or unique
// partial ID or name
func (s *SQLiteState) LookupContainerID(idOrName string) (string, error) {
if idOrName == "" {
return "", define.ErrEmptyID
}
if !s.valid {
return "", define.ErrDBClosed
}
rows, err := s.conn.Query("SELECT ID, Name FROM ContainerConfig WHERE ContainerConfig.Name=? OR (ContainerConfig.ID LIKE ?);", idOrName, idOrName+"%")
if err != nil {
return "", fmt.Errorf("looking up container %q in database: %w", idOrName, err)
}
defer rows.Close()
var (
id, name string
resCount uint
)
for rows.Next() {
if err := rows.Scan(&id, &name); err != nil {
return "", fmt.Errorf("retrieving container %q ID from database: %w", idOrName, err)
}
if name == idOrName {
return id, nil
}
resCount++
}
if err := rows.Err(); err != nil {
return "", err
}
if resCount == 0 {
return "", define.ErrNoSuchCtr
} else if resCount > 1 {
return "", fmt.Errorf("more than one result for container %q: %w", idOrName, define.ErrCtrExists)
}
return id, nil
}
// LookupContainer retrieves a container from the state by full or unique
// partial ID or name
func (s *SQLiteState) LookupContainer(idOrName string) (*Container, error) {
if idOrName == "" {
return nil, define.ErrEmptyID
}
if !s.valid {
return nil, define.ErrDBClosed
}
rows, err := s.conn.Query("SELECT JSON, Name FROM ContainerConfig WHERE ContainerConfig.Name=? OR (ContainerConfig.ID LIKE ?);", idOrName, idOrName+"%")
if err != nil {
return nil, fmt.Errorf("looking up container %q in database: %w", idOrName, err)
}
defer rows.Close()
var (
rawJSON, name string
exactName bool
resCount uint
)
for rows.Next() {
if err := rows.Scan(&rawJSON, &name); err != nil {
return nil, fmt.Errorf("retrieving container %q ID from database: %w", idOrName, err)
}
if name == idOrName {
exactName = true
break
}
resCount++
}
if err := rows.Err(); err != nil {
return nil, err
}
if !exactName {
if resCount == 0 {
return nil, fmt.Errorf("no container with name or ID %q found: %w", idOrName, define.ErrNoSuchCtr)
} else if resCount > 1 {
return nil, fmt.Errorf("more than one result for container %q: %w", idOrName, define.ErrCtrExists)
}
}
ctr := new(Container)
ctr.config = new(ContainerConfig)
ctr.state = new(ContainerState)
ctr.runtime = s.runtime
if err := json.Unmarshal([]byte(rawJSON), ctr.config); err != nil {
return nil, fmt.Errorf("unmarshalling container config JSON: %w", err)
}
if err := finalizeCtrSqlite(ctr); err != nil {
return nil, err
}
return ctr, nil
}
// HasContainer checks if a container is present in the state
func (s *SQLiteState) HasContainer(id string) (bool, error) {
if id == "" {
return false, define.ErrEmptyID
}
if !s.valid {
return false, define.ErrDBClosed
}
row := s.conn.QueryRow("SELECT 1 FROM ContainerConfig WHERE ID=?;", id)
var check int
if err := row.Scan(&check); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return false, nil
}
return false, fmt.Errorf("looking up container %s in database: %w", id, err)
} else if check != 1 {
return false, fmt.Errorf("check digit for container %s lookup incorrect: %w", id, define.ErrInternal)
}
return true, nil
}
// AddContainer adds a container to the state
// The container being added cannot belong to a pod
func (s *SQLiteState) AddContainer(ctr *Container) error {
if !s.valid {
return define.ErrDBClosed
}
if !ctr.valid {
return define.ErrCtrRemoved
}
if ctr.config.Pod != "" {
return fmt.Errorf("cannot add a container that belongs to a pod with AddContainer - use AddContainerToPod: %w", define.ErrInvalidArg)
}
return s.addContainer(ctr)
}
// RemoveContainer removes a container from the state
// Only removes containers not in pods - for containers that are a member of a
// pod, use RemoveContainerFromPod
func (s *SQLiteState) RemoveContainer(ctr *Container) error {
if !s.valid {
return define.ErrDBClosed
}
if ctr.config.Pod != "" {
return fmt.Errorf("container %s is part of a pod, use RemoveContainerFromPod instead: %w", ctr.ID(), define.ErrPodExists)
}
return s.removeContainer(ctr)
}
// UpdateContainer updates a container's state from the database
func (s *SQLiteState) UpdateContainer(ctr *Container) error {
if !s.valid {
return define.ErrDBClosed
}
if !ctr.valid {
return define.ErrCtrRemoved
}
row := s.conn.QueryRow("SELECT JSON FROM ContainerState WHERE ID=?;", ctr.ID())
var rawJSON string
if err := row.Scan(&rawJSON); err != nil {
if errors.Is(err, sql.ErrNoRows) {
// Container was removed
ctr.valid = false
return fmt.Errorf("no container with ID %s found in database: %w", ctr.ID(), define.ErrNoSuchCtr)
}
}
newState := new(ContainerState)
if err := json.Unmarshal([]byte(rawJSON), newState); err != nil {
return fmt.Errorf("unmarshalling container %s state JSON: %w", ctr.ID(), err)
}
ctr.state = newState
return nil
}
// SaveContainer saves a container's current state in the database
func (s *SQLiteState) SaveContainer(ctr *Container) (defErr error) {
if !s.valid {
return define.ErrDBClosed
}
if !ctr.valid {
return define.ErrCtrRemoved
}
stateJSON, err := json.Marshal(ctr.state)
if err != nil {
return fmt.Errorf("marshalling container %s state JSON: %w", ctr.ID(), err)
}
tx, err := s.conn.Begin()
if err != nil {
return fmt.Errorf("beginning container %s save transaction: %w", ctr.ID(), err)
}
defer func() {
if defErr != nil {
if err := tx.Rollback(); err != nil {
logrus.Errorf("Rolling back transaction to save container %s state: %v", ctr.ID(), err)
}
}
}()
result, err := tx.Exec("UPDATE ContainerState SET JSON=? WHERE ID=?;", stateJSON, ctr.ID())
if err != nil {
return fmt.Errorf("writing container %s state: %w", ctr.ID(), err)
}
rows, err := result.RowsAffected()
if err != nil {
return fmt.Errorf("retrieving container %s save rows affected: %w", ctr.ID(), err)
}
if rows == 0 {
ctr.valid = false
return define.ErrNoSuchCtr
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("committing container %s state: %w", ctr.ID(), err)
}
return nil
}
// ContainerInUse checks if other containers depend on the given container
// It returns a slice of the IDs of the containers depending on the given
// container. If the slice is empty, no containers depend on the given container
func (s *SQLiteState) ContainerInUse(ctr *Container) ([]string, error) {
if !s.valid {
return nil, define.ErrDBClosed
}
if !ctr.valid {
return nil, define.ErrCtrRemoved
}
rows, err := s.conn.Query("SELECT ID FROM ContainerDependency WHERE DependencyID=?;", ctr.ID())
if err != nil {
return nil, fmt.Errorf("retrieving containers that depend on container %s: %w", ctr.ID(), err)
}
defer rows.Close()
deps := []string{}
for rows.Next() {
var dep string
if err := rows.Scan(&dep); err != nil {
return nil, fmt.Errorf("reading containers that depend on %s: %w", ctr.ID(), err)
}
deps = append(deps, dep)
}
if err := rows.Err(); err != nil {
return nil, err
}
return deps, nil
}
// AllContainers retrieves all the containers in the database
// If `loadState` is set, the containers' state will be loaded as well.
func (s *SQLiteState) AllContainers(loadState bool) ([]*Container, error) {
if !s.valid {
return nil, define.ErrDBClosed
}
ctrs := []*Container{}
if loadState {
rows, err := s.conn.Query("SELECT ContainerConfig.JSON, ContainerState.JSON AS StateJSON FROM ContainerConfig INNER JOIN ContainerState ON ContainerConfig.ID = ContainerState.ID;")
if err != nil {
return nil, fmt.Errorf("retrieving all containers from database: %w", err)
}
defer rows.Close()
for rows.Next() {
var configJSON, stateJSON string
if err := rows.Scan(&configJSON, &stateJSON); err != nil {
return nil, fmt.Errorf("scanning container from database: %w", err)
}
ctr := new(Container)
ctr.config = new(ContainerConfig)
ctr.state = new(ContainerState)
ctr.runtime = s.runtime
if err := json.Unmarshal([]byte(configJSON), ctr.config); err != nil {
return nil, fmt.Errorf("unmarshalling container config: %w", err)
}
if err := json.Unmarshal([]byte(stateJSON), ctr.state); err != nil {
return nil, fmt.Errorf("unmarshalling container %s state: %w", ctr.ID(), err)
}
ctrs = append(ctrs, ctr)
}
if err := rows.Err(); err != nil {
return nil, err
}
} else {
rows, err := s.conn.Query("SELECT JSON FROM ContainerConfig;")
if err != nil {
return nil, fmt.Errorf("retrieving all containers from database: %w", err)
}
defer rows.Close()
for rows.Next() {
var rawJSON string
if err := rows.Scan(&rawJSON); err != nil {
return nil, fmt.Errorf("scanning container from database: %w", err)
}
ctr := new(Container)
ctr.config = new(ContainerConfig)
ctr.state = new(ContainerState)
ctr.runtime = s.runtime
if err := json.Unmarshal([]byte(rawJSON), ctr.config); err != nil {
return nil, fmt.Errorf("unmarshalling container config: %w", err)
}
ctrs = append(ctrs, ctr)
}
if err := rows.Err(); err != nil {
return nil, err
}
}
for _, ctr := range ctrs {
if err := finalizeCtrSqlite(ctr); err != nil {
return nil, err
}
}
return ctrs, nil
}
// GetNetworks returns the networks this container is a part of.
func (s *SQLiteState) GetNetworks(ctr *Container) (map[string]types.PerNetworkOptions, error) {
if !s.valid {
return nil, define.ErrDBClosed
}
if !ctr.valid {
return nil, define.ErrCtrRemoved
}
// if the network mode is not bridge return no networks
if !ctr.config.NetMode.IsBridge() {
return nil, nil
}
cfg, err := s.getCtrConfig(ctr.ID())
if err != nil {
if errors.Is(err, define.ErrNoSuchCtr) {
ctr.valid = false
}
return nil, err
}
return cfg.Networks, nil
}
// NetworkConnect adds the given container to the given network. If aliases are
// specified, those will be added to the given network.
func (s *SQLiteState) NetworkConnect(ctr *Container, network string, opts types.PerNetworkOptions) error {
return s.networkModify(ctr, network, opts, true, false)
}
// NetworkModify will allow you to set new options on an existing connected network
func (s *SQLiteState) NetworkModify(ctr *Container, network string, opts types.PerNetworkOptions) error {
return s.networkModify(ctr, network, opts, false, false)
}
// NetworkDisconnect disconnects the container from the given network, also
// removing any aliases in the network.
func (s *SQLiteState) NetworkDisconnect(ctr *Container, network string) error {
return s.networkModify(ctr, network, types.PerNetworkOptions{}, false, true)
}
// GetContainerConfig returns a container config from the database by full ID
func (s *SQLiteState) GetContainerConfig(id string) (*ContainerConfig, error) {
if len(id) == 0 {
return nil, define.ErrEmptyID
}
if !s.valid {
return nil, define.ErrDBClosed
}
return s.getCtrConfig(id)
}
// AddContainerExitCode adds the exit code for the specified container to the database.
func (s *SQLiteState) AddContainerExitCode(id string, exitCode int32) (defErr error) {
if len(id) == 0 {
return define.ErrEmptyID
}
if !s.valid {
return define.ErrDBClosed
}
tx, err := s.conn.Begin()
if err != nil {
return fmt.Errorf("beginning transaction to add exit code: %w", err)
}
defer func() {
if defErr != nil {
if err := tx.Rollback(); err != nil {
logrus.Errorf("Rolling back transaction to add exit code: %v", err)
}
}
}()
if _, err := tx.Exec("INSERT OR REPLACE INTO ContainerExitCode VALUES (?, ?, ?);", id, time.Now().Unix(), exitCode); err != nil {
return fmt.Errorf("adding container %s exit code %d: %w", id, exitCode, err)
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("committing transaction to add exit code: %w", err)
}
return nil
}
// GetContainerExitCode returns the exit code for the specified container.
func (s *SQLiteState) GetContainerExitCode(id string) (int32, error) {
if len(id) == 0 {
return -1, define.ErrEmptyID
}
if !s.valid {
return -1, define.ErrDBClosed
}
row := s.conn.QueryRow("SELECT ExitCode FROM ContainerExitCode WHERE ID=?;", id)
var exitCode int32 = -1
if err := row.Scan(&exitCode); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return -1, fmt.Errorf("getting exit code of container %s from DB: %w", id, define.ErrNoSuchExitCode)
}
return -1, fmt.Errorf("scanning exit code of container %s: %w", id, err)
}
return exitCode, nil
}
// GetContainerExitCodeTimeStamp returns the time stamp when the exit code of
// the specified container was added to the database.
func (s *SQLiteState) GetContainerExitCodeTimeStamp(id string) (*time.Time, error) {
if len(id) == 0 {
return nil, define.ErrEmptyID
}
if !s.valid {
return nil, define.ErrDBClosed
}
row := s.conn.QueryRow("SELECT Timestamp FROM ContainerExitCode WHERE ID=?;", id)
var timestamp int64
if err := row.Scan(×tamp); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, fmt.Errorf("getting timestamp for exit code of container %s from DB: %w", id, define.ErrNoSuchExitCode)
}
return nil, fmt.Errorf("scanning exit timestamp of container %s: %w", id, err)
}
result := time.Unix(timestamp, 0)
return &result, nil
}
// PruneContainerExitCodes removes exit codes older than 5 minutes unless the associated
// container still exists.
func (s *SQLiteState) PruneContainerExitCodes() (defErr error) {
if !s.valid {
return define.ErrDBClosed
}
fiveMinsAgo := time.Now().Add(-5 * time.Minute).Unix()
tx, err := s.conn.Begin()
if err != nil {
return fmt.Errorf("beginning transaction to remove old timestamps: %w", err)
}
defer func() {
if defErr != nil {
if err := tx.Rollback(); err != nil {
logrus.Errorf("Rolling back transaction to remove old timestamps: %v", err)
}
}
}()
if _, err := tx.Exec("DELETE FROM ContainerExitCode WHERE (Timestamp <= ?) AND (ID NOT IN (SELECT ID FROM ContainerConfig))", fiveMinsAgo); err != nil {
return fmt.Errorf("removing exit codes with timestamps older than 5 minutes: %w", err)
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("committing transaction to remove old timestamps: %w", err)
}
return nil
}
// AddExecSession adds an exec session to the state.
func (s *SQLiteState) AddExecSession(ctr *Container, session *ExecSession) (defErr error) {
if !s.valid {
return define.ErrDBClosed
}
if !ctr.valid {
return define.ErrCtrRemoved
}
tx, err := s.conn.Begin()
if err != nil {
return fmt.Errorf("beginning container %s exec session %s add transaction: %w", ctr.ID(), session.Id, err)
}
defer func() {
if defErr != nil {
if err := tx.Rollback(); err != nil {
logrus.Errorf("Rolling back transaction to add container %s exec session %s: %v", ctr.ID(), session.Id, err)
}
}
}()
if _, err := tx.Exec("INSERT INTO ContainerExecSession VALUES (?, ?);", session.Id, ctr.ID()); err != nil {
return fmt.Errorf("adding container %s exec session %s to database: %w", ctr.ID(), session.Id, err)
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("committing container %s exec session %s addition: %w", ctr.ID(), session.Id, err)
}
return nil
}
// GetExecSession returns the ID of the container an exec session is associated
// with.
func (s *SQLiteState) GetExecSession(id string) (string, error) {
if !s.valid {
return "", define.ErrDBClosed
}
if id == "" {
return "", define.ErrEmptyID
}
row := s.conn.QueryRow("SELECT ContainerID FROM ContainerExecSession WHERE ID=?;", id)
var ctrID string
if err := row.Scan(&ctrID); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return "", fmt.Errorf("no exec session with ID %s found: %w", id, define.ErrNoSuchExecSession)
}
return "", fmt.Errorf("retrieving exec session %s from database: %w", id, err)
}
return ctrID, nil
}
// RemoveExecSession removes references to the given exec session in the
// database.
func (s *SQLiteState) RemoveExecSession(session *ExecSession) (defErr error) {
if !s.valid {
return define.ErrDBClosed
}
tx, err := s.conn.Begin()
if err != nil {
return fmt.Errorf("beginning container %s exec session %s remove transaction: %w", session.ContainerId, session.Id, err)
}
defer func() {
if defErr != nil {
if err := tx.Rollback(); err != nil {
logrus.Errorf("Rolling back transaction to remove container %s exec session %s: %v", session.ContainerId, session.Id, err)
}
}
}()
result, err := tx.Exec("DELETE FROM ContainerExecSession WHERE ID=?;", session.Id)
if err != nil {
return fmt.Errorf("removing container %s exec session %s from database: %w", session.ContainerId, session.Id, err)
}
rows, err := result.RowsAffected()
if err != nil {
return fmt.Errorf("retrieving container %s exec session %s removal rows modified: %w", session.ContainerId, session.Id, err)
}
if rows == 0 {
return define.ErrNoSuchExecSession
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("committing container %s exec session %s removal: %w", session.ContainerId, session.Id, err)
}
return nil
}
// GetContainerExecSessions retrieves the IDs of all exec sessions running in a
// container that the database is aware of (IE, were added via AddExecSession).
func (s *SQLiteState) GetContainerExecSessions(ctr *Container) ([]string, error) {
if !s.valid {
return nil, define.ErrDBClosed
}
if !ctr.valid {
return nil, define.ErrCtrRemoved
}
rows, err := s.conn.Query("SELECT ID FROM ContainerExecSession WHERE ContainerID=?;", ctr.ID())
if err != nil {
return nil, fmt.Errorf("querying container %s exec sessions: %w", ctr.ID(), err)
}
defer rows.Close()
var sessions []string
for rows.Next() {
var session string
if err := rows.Scan(&session); err != nil {
return nil, fmt.Errorf("scanning container %s exec sessions row: %w", ctr.ID(), err)
}
sessions = append(sessions, session)
}
if err := rows.Err(); err != nil {
return nil, err
}
return sessions, nil
}
// RemoveContainerExecSessions removes all exec sessions attached to a given
// container.
func (s *SQLiteState) RemoveContainerExecSessions(ctr *Container) (defErr error) {
if !s.valid {
return define.ErrDBClosed
}
if !ctr.valid {
return define.ErrCtrRemoved
}
tx, err := s.conn.Begin()
if err != nil {
return fmt.Errorf("beginning container %s exec session removal transaction: %w", ctr.ID(), err)
}
defer func() {
if defErr != nil {
if err := tx.Rollback(); err != nil {
logrus.Errorf("Rolling back transaction to remove container %s exec sessions: %v", ctr.ID(), err)
}
}
}()
if _, err := tx.Exec("DELETE FROM ContainerExecSession WHERE ContainerID=?;", ctr.ID()); err != nil {
return fmt.Errorf("removing container %s exec sessions from database: %w", ctr.ID(), err)
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("committing container %s exec session removal: %w", ctr.ID(), err)
}
return nil
}
// RewriteContainerConfig rewrites a container's configuration.
// DO NOT USE TO: Change container dependencies, change pod membership, change
// container ID.
// WARNING: This function is DANGEROUS. Do not use without reading the full
// comment on this function in state.go.
// TODO: Once BoltDB is removed, this can be combined with SafeRewriteContainerConfig.
func (s *SQLiteState) RewriteContainerConfig(ctr *Container, newCfg *ContainerConfig) error {
if !s.valid {
return define.ErrDBClosed
}
if !ctr.valid {
return define.ErrCtrRemoved
}
return s.rewriteContainerConfig(ctr, newCfg)
}
// SafeRewriteContainerConfig rewrites a container's configuration in a more
// limited fashion than RewriteContainerConfig. It is marked as safe to use
// under most circumstances, unlike RewriteContainerConfig.
// DO NOT USE TO: Change container dependencies, change pod membership, change
// locks, change container ID.
// TODO: Once BoltDB is removed, this can be combined with RewriteContainerConfig.
func (s *SQLiteState) SafeRewriteContainerConfig(ctr *Container, oldName, newName string, newCfg *ContainerConfig) error {
if !s.valid {
return define.ErrDBClosed
}
if !ctr.valid {
return define.ErrCtrRemoved
}
if newName != "" && newCfg.Name != newName {
return fmt.Errorf("new name %s for container %s must match name in given container config: %w", newName, ctr.ID(), define.ErrInvalidArg)
}
if newName != "" && oldName == "" {
return fmt.Errorf("must provide old name for container if a new name is given: %w", define.ErrInvalidArg)
}
return s.rewriteContainerConfig(ctr, newCfg)
}
// RewritePodConfig rewrites a pod's configuration.
// WARNING: This function is DANGEROUS. Do not use without reading the full
// comment on this function in state.go.
func (s *SQLiteState) RewritePodConfig(pod *Pod, newCfg *PodConfig) (defErr error) {
if !s.valid {
return define.ErrDBClosed
}
if !pod.valid {
return define.ErrPodRemoved
}
json, err := json.Marshal(newCfg)
if err != nil {
return fmt.Errorf("error marshalling pod %s config JSON: %w", pod.ID(), err)
}
tx, err := s.conn.Begin()
if err != nil {
return fmt.Errorf("beginning transaction to rewrite pod %s config: %w", pod.ID(), err)
}
defer func() {
if defErr != nil {
if err := tx.Rollback(); err != nil {
logrus.Errorf("Rolling back transaction to rewrite pod %s config: %v", pod.ID(), err)
}
}
}()
results, err := tx.Exec("UPDATE PodConfig SET Name=?, JSON=? WHERE ID=?;", newCfg.Name, json, pod.ID())
if err != nil {
return fmt.Errorf("updating pod config table with new configuration for pod %s: %w", pod.ID(), err)
}
rows, err := results.RowsAffected()
if err != nil {
return fmt.Errorf("retrieving pod %s config rewrite rows affected: %w", pod.ID(), err)
}
if rows == 0 {
pod.valid = false
return fmt.Errorf("no pod with ID %s found in DB: %w", pod.ID(), define.ErrNoSuchPod)
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("committing transaction to rewrite pod %s config: %w", pod.ID(), err)
}
return nil
}
// RewriteVolumeConfig rewrites a volume's configuration.
// WARNING: This function is DANGEROUS. Do not use without reading the full
// comment on this function in state.go.
func (s *SQLiteState) RewriteVolumeConfig(volume *Volume, newCfg *VolumeConfig) (defErr error) {
if !s.valid {
return define.ErrDBClosed
}
if !volume.valid {
return define.ErrVolumeRemoved
}
json, err := json.Marshal(newCfg)
if err != nil {
return fmt.Errorf("error marshalling volume %s new config JSON: %w", volume.Name(), err)
}
tx, err := s.conn.Begin()
if err != nil {
return fmt.Errorf("beginning transaction to rewrite volume %s config: %w", volume.Name(), err)
}
defer func() {
if defErr != nil {
if err := tx.Rollback(); err != nil {
logrus.Errorf("Rolling back transaction to rewrite volume %s config: %v", volume.Name(), err)
}
}
}()
results, err := tx.Exec("UPDATE VolumeConfig SET Name=?, JSON=? WHERE Name=?;", newCfg.Name, json, volume.Name())
if err != nil {
return fmt.Errorf("updating volume config table with new configuration for volume %s: %w", volume.Name(), err)
}
rows, err := results.RowsAffected()
if err != nil {
return fmt.Errorf("retrieving volume %s config rewrite rows affected: %w", volume.Name(), err)
}
if rows == 0 {
volume.valid = false
return fmt.Errorf("no volume with name %q found in DB: %w", volume.Name(), define.ErrNoSuchVolume)
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("committing transaction to rewrite volume %s config: %w", volume.Name(), err)
}
return nil
}
// Pod retrieves a pod given its full ID
func (s *SQLiteState) Pod(id string) (*Pod, error) {
if id == "" {
return nil, define.ErrEmptyID
}
if !s.valid {
return nil, define.ErrDBClosed
}
row := s.conn.QueryRow("SELECT JSON FROM PodConfig WHERE ID=?;", id)
var rawJSON string
if err := row.Scan(&rawJSON); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, define.ErrNoSuchPod
}
return nil, fmt.Errorf("retrieving pod %s config from DB: %w", id, err)
}
ctrCfg := new(ContainerConfig)
if err := json.Unmarshal([]byte(rawJSON), ctrCfg); err != nil {
return nil, fmt.Errorf("unmarshalling container %s config: %w", id, err)
}
return s.createPod(rawJSON)
}
// LookupPod retrieves a pod from a full or unique partial ID, or a name.
func (s *SQLiteState) LookupPod(idOrName string) (*Pod, error) {
if idOrName == "" {
return nil, define.ErrEmptyID
}
if !s.valid {
return nil, define.ErrDBClosed
}
rows, err := s.conn.Query("SELECT JSON, Name FROM PodConfig WHERE PodConfig.Name=? OR (PodConfig.ID LIKE ?);", idOrName, idOrName+"%")
if err != nil {
return nil, fmt.Errorf("looking up pod %q in database: %w", idOrName, err)
}
defer rows.Close()
var (
rawJSON, name string
exactName bool
resCount uint
)
for rows.Next() {
if err := rows.Scan(&rawJSON, &name); err != nil {
return nil, fmt.Errorf("error retrieving pod %q ID from database: %w", idOrName, err)
}
if name == idOrName {
exactName = true
break
}
resCount++
}
if err := rows.Err(); err != nil {
return nil, err
}
if !exactName {
if resCount == 0 {
return nil, fmt.Errorf("no pod with name or ID %s found: %w", idOrName, define.ErrNoSuchPod)
} else if resCount > 1 {
return nil, fmt.Errorf("more than one result for pod %q: %w", idOrName, define.ErrCtrExists)
}
}
return s.createPod(rawJSON)
}
// HasPod checks if a pod with the given ID exists in the state
func (s *SQLiteState) HasPod(id string) (bool, error) {
if id == "" {
return false, define.ErrEmptyID
}
if !s.valid {
return false, define.ErrDBClosed
}
row := s.conn.QueryRow("SELECT 1 FROM PodConfig WHERE ID=?;", id)
var check int
if err := row.Scan(&check); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return false, nil
}
return false, fmt.Errorf("looking up pod %s in database: %w", id, err)
} else if check != 1 {
return false, fmt.Errorf("check digit for pod %s lookup incorrect: %w", id, define.ErrInternal)
}
return true, nil
}
// PodHasContainer checks if the given pod has a container with the given ID
func (s *SQLiteState) PodHasContainer(pod *Pod, id string) (bool, error) {
if id == "" {
return false, define.ErrEmptyID
}
if !s.valid {
return false, define.ErrDBClosed
}
if !pod.valid {
return false, define.ErrPodRemoved
}
var check int
row := s.conn.QueryRow("SELECT 1 FROM ContainerConfig WHERE ID=? AND PodID=?;", id, pod.ID())
if err := row.Scan(&check); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return false, nil
}
return false, fmt.Errorf("checking if pod %s has container %s in database: %w", pod.ID(), id, err)
} else if check != 1 {
return false, fmt.Errorf("check digit for pod %s lookup incorrect: %w", id, define.ErrInternal)
}
return true, nil
}
// PodContainersByID returns the IDs of all containers present in the given pod
func (s *SQLiteState) PodContainersByID(pod *Pod) ([]string, error) {
if !s.valid {
return nil, define.ErrDBClosed
}
if !pod.valid {
return nil, define.ErrPodRemoved
}
rows, err := s.conn.Query("SELECT ID FROM ContainerConfig WHERE PodID=?;", pod.ID())
if err != nil {
return nil, fmt.Errorf("retrieving container IDs of pod %s from database: %w", pod.ID(), err)
}
defer rows.Close()
var ids []string
for rows.Next() {
var id string
if err := rows.Scan(&id); err != nil {
return nil, fmt.Errorf("scanning container from database: %w", err)
}
ids = append(ids, id)
}
if err := rows.Err(); err != nil {
return nil, err
}
return ids, nil
}
// PodContainers returns all the containers present in the given pod
func (s *SQLiteState) PodContainers(pod *Pod) ([]*Container, error) {
if !s.valid {
return nil, define.ErrDBClosed
}
if !pod.valid {
return nil, define.ErrPodRemoved
}
rows, err := s.conn.Query("SELECT JSON FROM ContainerConfig WHERE PodID=?;", pod.ID())
if err != nil {
return nil, fmt.Errorf("retrieving containers of pod %s from database: %w", pod.ID(), err)
}
defer rows.Close()
var ctrs []*Container
for rows.Next() {
var rawJSON string
if err := rows.Scan(&rawJSON); err != nil {
return nil, fmt.Errorf("scanning container from database: %w", err)
}
ctr := new(Container)
ctr.config = new(ContainerConfig)
ctr.state = new(ContainerState)
ctr.runtime = s.runtime
if err := json.Unmarshal([]byte(rawJSON), ctr.config); err != nil {
return nil, fmt.Errorf("unmarshalling container config: %w", err)
}
ctrs = append(ctrs, ctr)
}
if err := rows.Err(); err != nil {
return nil, err
}
for _, ctr := range ctrs {
if err := finalizeCtrSqlite(ctr); err != nil {
return nil, err
}
}
return ctrs, nil
}
// AddPod adds the given pod to the state.
func (s *SQLiteState) AddPod(pod *Pod) (defErr error) {
if !s.valid {
return define.ErrDBClosed
}
if !pod.valid {
return define.ErrPodRemoved
}
infraID := sql.NullString{}
if pod.state.InfraContainerID != "" {
if err := infraID.Scan(pod.state.InfraContainerID); err != nil {
return fmt.Errorf("scanning infra container ID %q: %w", pod.state.InfraContainerID, err)
}
}
configJSON, err := json.Marshal(pod.config)
if err != nil {
return fmt.Errorf("marshalling pod config json: %w", err)
}
stateJSON, err := json.Marshal(pod.state)
if err != nil {
return fmt.Errorf("marshalling pod state json: %w", err)
}
tx, err := s.conn.Begin()
if err != nil {
return fmt.Errorf("beginning pod create transaction: %w", err)
}
defer func() {
if defErr != nil {
if err := tx.Rollback(); err != nil {
logrus.Errorf("Rolling back transaction to create pod: %v", err)
}
}
}()
// TODO: explore whether there's a more idiomatic way to do error checks for the name.
// There is a sqlite3.ErrConstraintUnique error but I (vrothberg) couldn't find a way
// to work with the returned errors yet.
var check int
row := tx.QueryRow("SELECT 1 FROM PodConfig WHERE Name=?;", pod.Name())
if err := row.Scan(&check); err != nil {
if !errors.Is(err, sql.ErrNoRows) {
return fmt.Errorf("checking if pod name %s exists in database: %w", pod.Name(), err)
}
} else if check != 0 {
return fmt.Errorf("name %q is in use: %w", pod.Name(), define.ErrPodExists)
}
if _, err := tx.Exec("INSERT INTO IDNamespace VALUES (?);", pod.ID()); err != nil {
return fmt.Errorf("adding pod id to database: %w", err)
}
if _, err := tx.Exec("INSERT INTO PodConfig VALUES (?, ?, ?);", pod.ID(), pod.Name(), configJSON); err != nil {
return fmt.Errorf("adding pod config to database: %w", err)
}
if _, err := tx.Exec("INSERT INTO PodState VALUES (?, ?, ?);", pod.ID(), infraID, stateJSON); err != nil {
return fmt.Errorf("adding pod state to database: %w", err)
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("committing transaction: %w", err)
}
return nil
}
// RemovePod removes the given pod from the state.
// Only empty pods can be removed.
func (s *SQLiteState) RemovePod(pod *Pod) (defErr error) {
if !s.valid {
return define.ErrDBClosed
}
if !pod.valid {
return define.ErrPodRemoved
}
tx, err := s.conn.Begin()
if err != nil {
return fmt.Errorf("beginning pod %s removal transaction: %w", pod.ID(), err)
}
defer func() {
if defErr != nil {
if err := tx.Rollback(); err != nil {
logrus.Errorf("Rolling back transaction to remove pod %s: %v", pod.ID(), err)
}
}
}()
var check int
row := tx.QueryRow("SELECT 1 FROM ContainerConfig WHERE PodID=? AND ID!=?;", pod.ID(), pod.state.InfraContainerID)
if err := row.Scan(&check); err != nil {
if !errors.Is(err, sql.ErrNoRows) {
return fmt.Errorf("checking if pod %s has containers in database: %w", pod.ID(), err)
}
} else if check != 0 {
return fmt.Errorf("pod %s is not empty: %w", pod.ID(), define.ErrCtrExists)
}
checkResult := func(result sql.Result) error {
rows, err := result.RowsAffected()
if err != nil {
return fmt.Errorf("retrieving pod %s delete rows affected: %w", pod.ID(), err)
}
if rows == 0 {
pod.valid = false
return define.ErrNoSuchPod
}
return nil
}
result, err := tx.Exec("DELETE FROM IDNamespace WHERE ID=?;", pod.ID())
if err != nil {
return fmt.Errorf("removing pod %s id from database: %w", pod.ID(), err)
}
if err := checkResult(result); err != nil {
return err
}
result, err = tx.Exec("DELETE FROM PodConfig WHERE ID=?;", pod.ID())
if err != nil {
return fmt.Errorf("removing pod %s config from database: %w", pod.ID(), err)
}
if err := checkResult(result); err != nil {
return err
}
result, err = tx.Exec("DELETE FROM PodState WHERE ID=?;", pod.ID())
if err != nil {
return fmt.Errorf("removing pod %s state from database: %w", pod.ID(), err)
}
if err := checkResult(result); err != nil {
return err
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("committing pod %s removal transaction: %w", pod.ID(), err)
}
return nil
}
// RemovePodContainers removes all containers in a pod.
func (s *SQLiteState) RemovePodContainers(pod *Pod) (defErr error) {
if !s.valid {
return define.ErrDBClosed
}
if !pod.valid {
return define.ErrPodRemoved
}
tx, err := s.conn.Begin()
if err != nil {
return fmt.Errorf("beginning removal transaction for containers of pod %s: %w", pod.ID(), err)
}
defer func() {
if defErr != nil {
if err := tx.Rollback(); err != nil {
logrus.Errorf("Rolling back transaction to remove containers of pod %s: %v", pod.ID(), err)
}
}
}()
rows, err := tx.Query("SELECT ID FROM ContainerConfig WHERE PodID=?;", pod.ID())
if err != nil {
return fmt.Errorf("retrieving container IDs of pod %s from database: %w", pod.ID(), err)
}
defer rows.Close()
for rows.Next() {
var id string
if err := rows.Scan(&id); err != nil {
return fmt.Errorf("scanning container from database: %w", err)
}
if err := s.removeContainerWithTx(id, tx); err != nil {
return err
}
}
if err := rows.Err(); err != nil {
return err
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("committing pod containers %s removal transaction: %w", pod.ID(), err)
}
return nil
}
// AddContainerToPod adds the given container to an existing pod
// The container will be added to the state and the pod
func (s *SQLiteState) AddContainerToPod(pod *Pod, ctr *Container) error {
if !s.valid {
return define.ErrDBClosed
}
if !pod.valid {
return define.ErrPodRemoved
}
if !ctr.valid {
return define.ErrCtrRemoved
}
if ctr.config.Pod != pod.ID() {
return fmt.Errorf("container %s is not part of pod %s: %w", ctr.ID(), pod.ID(), define.ErrNoSuchCtr)
}
return s.addContainer(ctr)
}
// RemoveContainerFromPod removes a container from an existing pod
// The container will also be removed from the state
func (s *SQLiteState) RemoveContainerFromPod(pod *Pod, ctr *Container) error {
if !s.valid {
return define.ErrDBClosed
}
if !pod.valid {
return define.ErrPodRemoved
}
if ctr.config.Pod == "" {
return fmt.Errorf("container %s is not part of a pod, use RemoveContainer instead: %w", ctr.ID(), define.ErrNoSuchPod)
}
if ctr.config.Pod != pod.ID() {
return fmt.Errorf("container %s is not part of pod %s: %w", ctr.ID(), pod.ID(), define.ErrInvalidArg)
}
return s.removeContainer(ctr)
}
// UpdatePod updates a pod's state from the database.
func (s *SQLiteState) UpdatePod(pod *Pod) error {
if !s.valid {
return define.ErrDBClosed
}
if !pod.valid {
return define.ErrPodRemoved
}
row := s.conn.QueryRow("SELECT JSON FROM PodState WHERE ID=?;", pod.ID())
var rawJSON string
if err := row.Scan(&rawJSON); err != nil {
if errors.Is(err, sql.ErrNoRows) {
// Pod was removed
pod.valid = false
return fmt.Errorf("no pod with ID %s found in database: %w", pod.ID(), define.ErrNoSuchPod)
}
}
newState := new(podState)
if err := json.Unmarshal([]byte(rawJSON), newState); err != nil {
return fmt.Errorf("unmarshalling pod %s state JSON: %w", pod.ID(), err)
}
pod.state = newState
return nil
}
// SavePod saves a pod's state to the database.
func (s *SQLiteState) SavePod(pod *Pod) (defErr error) {
if !s.valid {
return define.ErrDBClosed
}
if !pod.valid {
return define.ErrPodRemoved
}
stateJSON, err := json.Marshal(pod.state)
if err != nil {
return fmt.Errorf("marshalling pod %s state JSON: %w", pod.ID(), err)
}
tx, err := s.conn.Begin()
if err != nil {
return fmt.Errorf("beginning pod %s save transaction: %w", pod.ID(), err)
}
defer func() {
if defErr != nil {
if err := tx.Rollback(); err != nil {
logrus.Errorf("Rolling back transaction to save pod %s state: %v", pod.ID(), err)
}
}
}()
result, err := tx.Exec("UPDATE PodState SET JSON=? WHERE ID=?;", stateJSON, pod.ID())
if err != nil {
return fmt.Errorf("writing pod %s state: %w", pod.ID(), err)
}
rows, err := result.RowsAffected()
if err != nil {
return fmt.Errorf("retrieving pod %s save rows affected: %w", pod.ID(), err)
}
if rows == 0 {
pod.valid = false
return define.ErrNoSuchPod
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("committing pod %s state: %w", pod.ID(), err)
}
return nil
}
// AllPods returns all pods present in the state.
func (s *SQLiteState) AllPods() ([]*Pod, error) {
if !s.valid {
return nil, define.ErrDBClosed
}
pods := []*Pod{}
rows, err := s.conn.Query("SELECT JSON FROM PodConfig;")
if err != nil {
return nil, fmt.Errorf("retrieving all pods from database: %w", err)
}
defer rows.Close()
for rows.Next() {
var rawJSON string
if err := rows.Scan(&rawJSON); err != nil {
return nil, fmt.Errorf("scanning pod from database: %w", err)
}
pod, err := s.createPod(rawJSON)
if err != nil {
return nil, err
}
pods = append(pods, pod)
}
if err := rows.Err(); err != nil {
return nil, err
}
return pods, nil
}
// AddVolume adds the given volume to the state. It also adds ctrDepID to
// the sub bucket holding the container dependencies that this volume has
func (s *SQLiteState) AddVolume(volume *Volume) (defErr error) {
if !s.valid {
return define.ErrDBClosed
}
if !volume.valid {
return define.ErrVolumeRemoved
}
cfgJSON, err := json.Marshal(volume.config)
if err != nil {
return fmt.Errorf("marshalling volume %s configuration json: %w", volume.Name(), err)
}
volState := volume.state
if volState == nil {
volState = new(VolumeState)
}
stateJSON, err := json.Marshal(volState)
if err != nil {
return fmt.Errorf("marshalling volume %s state json: %w", volume.Name(), err)
}
storageID := sql.NullString{}
if volume.config.StorageID != "" {
storageID.Valid = true
storageID.String = volume.config.StorageID
}
tx, err := s.conn.Begin()
if err != nil {
return fmt.Errorf("beginning volume create transaction: %w", err)
}
defer func() {
if defErr != nil {
if err := tx.Rollback(); err != nil {
logrus.Errorf("Rolling back transaction to create volume: %v", err)
}
}
}()
// TODO: There has to be a better way of doing this
var check int
row := tx.QueryRow("SELECT 1 FROM VolumeConfig WHERE Name=?;", volume.Name())
if err := row.Scan(&check); err != nil {
if !errors.Is(err, sql.ErrNoRows) {
return fmt.Errorf("checking if volume name %s exists in database: %w", volume.Name(), err)
}
} else if check != 0 {
return fmt.Errorf("name %q is in use: %w", volume.Name(), define.ErrVolumeExists)
}
if _, err := tx.Exec("INSERT INTO VolumeConfig VALUES (?, ?, ?);", volume.Name(), storageID, cfgJSON); err != nil {
return fmt.Errorf("adding volume %s config to database: %w", volume.Name(), err)
}
if _, err := tx.Exec("INSERT INTO VolumeState VALUES (?, ?);", volume.Name(), stateJSON); err != nil {
return fmt.Errorf("adding volume %s state to database: %w", volume.Name(), err)
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("committing transaction: %w", err)
}
return nil
}
// RemoveVolume removes the given volume from the state
func (s *SQLiteState) RemoveVolume(volume *Volume) (defErr error) {
if !s.valid {
return define.ErrDBClosed
}
tx, err := s.conn.Begin()
if err != nil {
return fmt.Errorf("beginning volume %s removal transaction: %w", volume.Name(), err)
}
defer func() {
if defErr != nil {
if err := tx.Rollback(); err != nil {
logrus.Errorf("Rolling back transaction to remove volume %s: %v", volume.Name(), err)
}
}
}()
rows, err := tx.Query("SELECT ContainerID FROM ContainerVolume WHERE VolumeName=?;", volume.Name())
if err != nil {
return fmt.Errorf("querying for containers using volume %s: %w", volume.Name(), err)
}
defer rows.Close()
var ctrs []string
for rows.Next() {
var ctr string
if err := rows.Scan(&ctr); err != nil {
return fmt.Errorf("error scanning row for containers using volume %s: %w", volume.Name(), err)
}
ctrs = append(ctrs, ctr)
}
if err := rows.Err(); err != nil {
return err
}
if len(ctrs) > 0 {
return fmt.Errorf("volume %s is in use by containers %s: %w", volume.Name(), strings.Join(ctrs, ","), define.ErrVolumeBeingUsed)
}
// TODO TODO TODO:
// Need to verify that at least 1 row was deleted from VolumeConfig.
// Otherwise return ErrNoSuchVolume
if _, err := tx.Exec("DELETE FROM VolumeConfig WHERE Name=?;", volume.Name()); err != nil {
return fmt.Errorf("removing volume %s config from DB: %w", volume.Name(), err)
}
if _, err := tx.Exec("DELETE FROM VolumeState WHERE Name=?;", volume.Name()); err != nil {
return fmt.Errorf("removing volume %s state from DB: %w", volume.Name(), err)
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("committing transaction to remove volume %s: %w", volume.Name(), err)
}
return nil
}
// UpdateVolume updates the volume's state from the database.
func (s *SQLiteState) UpdateVolume(volume *Volume) error {
if !s.valid {
return define.ErrDBClosed
}
if !volume.valid {
return define.ErrVolumeRemoved
}
row := s.conn.QueryRow("SELECT JSON FROM VolumeState WHERE Name=?;", volume.Name())
var stateJSON string
if err := row.Scan(&stateJSON); err != nil {
if errors.Is(err, sql.ErrNoRows) {
volume.valid = false
return define.ErrNoSuchVolume
}
return fmt.Errorf("scanning volume %s state JSON: %w", volume.Name(), err)
}
newState := new(VolumeState)
if err := json.Unmarshal([]byte(stateJSON), newState); err != nil {
return fmt.Errorf("unmarshalling volume %s state: %w", volume.Name(), err)
}
volume.state = newState
return nil
}
// SaveVolume saves the volume's state to the database.
func (s *SQLiteState) SaveVolume(volume *Volume) (defErr error) {
if !s.valid {
return define.ErrDBClosed
}
if !volume.valid {
return define.ErrVolumeRemoved
}
stateJSON, err := json.Marshal(volume.state)
if err != nil {
return fmt.Errorf("marshalling volume %s state JSON: %w", volume.Name(), err)
}
tx, err := s.conn.Begin()
if err != nil {
return fmt.Errorf("beginning transaction to rewrite volume %s state: %w", volume.Name(), err)
}
defer func() {
if defErr != nil {
if err := tx.Rollback(); err != nil {
logrus.Errorf("Rolling back transaction to rewrite volume %s state: %v", volume.Name(), err)
}
}
}()
results, err := tx.Exec("UPDATE VolumeState SET JSON=? WHERE Name=?;", stateJSON, volume.Name())
if err != nil {
return fmt.Errorf("updating volume %s state in DB: %w", volume.Name(), err)
}
rows, err := results.RowsAffected()
if err != nil {
return fmt.Errorf("retrieving volume %s state rewrite rows affected: %w", volume.Name(), err)
}
if rows == 0 {
volume.valid = false
return define.ErrNoSuchVolume
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("committing transaction to rewrite volume %s state: %w", volume.Name(), err)
}
return nil
}
// AllVolumes returns all volumes present in the state.
func (s *SQLiteState) AllVolumes() ([]*Volume, error) {
if !s.valid {
return nil, define.ErrDBClosed
}
rows, err := s.conn.Query("SELECT JSON FROM VolumeConfig;")
if err != nil {
return nil, fmt.Errorf("querying database for all volumes: %w", err)
}
defer rows.Close()
var volumes []*Volume
for rows.Next() {
var configJSON string
if err := rows.Scan(&configJSON); err != nil {
return nil, fmt.Errorf("scanning volume config from database: %w", err)
}
vol := new(Volume)
vol.config = new(VolumeConfig)
vol.state = new(VolumeState)
vol.runtime = s.runtime
if err := json.Unmarshal([]byte(configJSON), vol.config); err != nil {
return nil, fmt.Errorf("unmarshalling volume config: %w", err)
}
if err := finalizeVolumeSqlite(vol); err != nil {
return nil, err
}
volumes = append(volumes, vol)
}
if err := rows.Err(); err != nil {
return nil, err
}
return volumes, nil
}
// Volume retrieves a volume from full name.
func (s *SQLiteState) Volume(name string) (*Volume, error) {
if name == "" {
return nil, define.ErrEmptyID
}
if !s.valid {
return nil, define.ErrDBClosed
}
row := s.conn.QueryRow("SELECT JSON FROM VolumeConfig WHERE Name=?;", name)
var configJSON string
if err := row.Scan(&configJSON); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, define.ErrNoSuchVolume
}
return nil, fmt.Errorf("querying volume %s: %w", name, err)
}
vol := new(Volume)
vol.config = new(VolumeConfig)
vol.state = new(VolumeState)
vol.runtime = s.runtime
if err := json.Unmarshal([]byte(configJSON), vol.config); err != nil {
return nil, fmt.Errorf("unmarshalling volume %s config JSON: %w", name, err)
}
if err := finalizeVolumeSqlite(vol); err != nil {
return nil, err
}
return vol, nil
}
// LookupVolume locates a volume from a unique partial name.
func (s *SQLiteState) LookupVolume(name string) (*Volume, error) {
if name == "" {
return nil, define.ErrEmptyID
}
if !s.valid {
return nil, define.ErrDBClosed
}
rows, err := s.conn.Query("SELECT Name, JSON FROM VolumeConfig WHERE Name LIKE ? ORDER BY LENGTH(Name) ASC;", name+"%")
if err != nil {
return nil, fmt.Errorf("querying database for volume %s: %w", name, err)
}
defer rows.Close()
var foundName, configJSON string
for rows.Next() {
if foundName != "" {
return nil, fmt.Errorf("more than one result for volume name %s: %w", name, define.ErrVolumeExists)
}
if err := rows.Scan(&foundName, &configJSON); err != nil {
return nil, fmt.Errorf("retrieving volume %s config from database: %w", name, err)
}
if foundName == name {
break
}
}
if err := rows.Err(); err != nil {
return nil, err
}
if foundName == "" {
return nil, fmt.Errorf("no volume with name %q found: %w", name, define.ErrNoSuchVolume)
}
vol := new(Volume)
vol.config = new(VolumeConfig)
vol.state = new(VolumeState)
vol.runtime = s.runtime
if err := json.Unmarshal([]byte(configJSON), vol.config); err != nil {
return nil, fmt.Errorf("unmarshalling volume %s config JSON: %w", name, err)
}
if err := finalizeVolumeSqlite(vol); err != nil {
return nil, err
}
return vol, nil
}
// HasVolume returns true if the given volume exists in the state.
// Otherwise it returns false.
func (s *SQLiteState) HasVolume(name string) (bool, error) {
if name == "" {
return false, define.ErrEmptyID
}
if !s.valid {
return false, define.ErrDBClosed
}
row := s.conn.QueryRow("SELECT 1 FROM VolumeConfig WHERE Name=?;", name)
var check int
if err := row.Scan(&check); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return false, nil
}
return false, fmt.Errorf("looking up volume %s in database: %w", name, err)
}
if check != 1 {
return false, fmt.Errorf("check digit for volume %s lookup incorrect: %w", name, define.ErrInternal)
}
return true, nil
}
// VolumeInUse checks if any container is using the volume.
// It returns a slice of the IDs of the containers using the given
// volume. If the slice is empty, no containers use the given volume.
func (s *SQLiteState) VolumeInUse(volume *Volume) ([]string, error) {
if !s.valid {
return nil, define.ErrDBClosed
}
if !volume.valid {
return nil, define.ErrVolumeRemoved
}
rows, err := s.conn.Query("SELECT ContainerID FROM ContainerVolume WHERE VolumeName=?;", volume.Name())
if err != nil {
return nil, fmt.Errorf("querying database for containers using volume %s: %w", volume.Name(), err)
}
defer rows.Close()
var ctrs []string
for rows.Next() {
var ctr string
if err := rows.Scan(&ctr); err != nil {
return nil, fmt.Errorf("scanning container ID for container using volume %s: %w", volume.Name(), err)
}
ctrs = append(ctrs, ctr)
}
if err := rows.Err(); err != nil {
return nil, err
}
return ctrs, nil
}
// ContainerIDIsVolume checks if the given c/storage container ID is used as
// backing storage for a volume.
func (s *SQLiteState) ContainerIDIsVolume(id string) (bool, error) {
if !s.valid {
return false, define.ErrDBClosed
}
row := s.conn.QueryRow("SELECT 1 FROM VolumeConfig WHERE StorageID=?;", id)
var checkDigit int
if err := row.Scan(&checkDigit); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return false, nil
}
return false, fmt.Errorf("error retrieving volumes using storage ID %s: %w", id, err)
}
if checkDigit != 1 {
return false, fmt.Errorf("check digit for volumes using storage ID %s was incorrect: %w", id, define.ErrInternal)
}
return true, nil
}
|