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
|
/*
Copyright 2017 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package spanner
import (
"bytes"
"container/heap"
"context"
"fmt"
"io/ioutil"
"log"
"math/rand"
"os"
"strings"
"testing"
"time"
. "cloud.google.com/go/spanner/internal/testutil"
"google.golang.org/api/iterator"
"google.golang.org/genproto/googleapis/rpc/errdetails"
sppb "google.golang.org/genproto/googleapis/spanner/v1"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
func newSessionNotFoundError(name string) error {
s := status.Newf(codes.NotFound, "Session not found: Session with id %s not found", name)
s, _ = s.WithDetails(&errdetails.ResourceInfo{ResourceType: sessionResourceType, ResourceName: name})
return s.Err()
}
// TestSessionPoolConfigValidation tests session pool config validation.
func TestSessionPoolConfigValidation(t *testing.T) {
t.Parallel()
_, client, teardown := setupMockedTestServer(t)
defer teardown()
for _, test := range []struct {
spc SessionPoolConfig
err error
}{
{
SessionPoolConfig{
MinOpened: 10,
MaxOpened: 5,
},
errMinOpenedGTMaxOpened(5, 10),
},
{
SessionPoolConfig{
WriteSessions: -0.1,
},
errWriteFractionOutOfRange(-0.1),
},
{
SessionPoolConfig{
WriteSessions: 2.0,
},
errWriteFractionOutOfRange(2.0),
},
{
SessionPoolConfig{
HealthCheckWorkers: -1,
},
errHealthCheckWorkersNegative(-1),
},
{
SessionPoolConfig{
HealthCheckInterval: -time.Second,
},
errHealthCheckIntervalNegative(-time.Second),
},
} {
if _, err := newSessionPool(client.sc, test.spc); !testEqual(err, test.err) {
t.Fatalf("want %v, got %v", test.err, err)
}
}
}
// TestSessionCreation tests session creation during sessionPool.Take().
func TestSessionCreation(t *testing.T) {
t.Parallel()
ctx := context.Background()
server, client, teardown := setupMockedTestServer(t)
defer teardown()
sp := client.idleSessions
// Take three sessions from session pool, this should trigger session pool
// to create three new sessions.
shs := make([]*sessionHandle, 3)
// gotDs holds the unique sessions taken from session pool.
gotDs := map[string]bool{}
for i := 0; i < len(shs); i++ {
var err error
shs[i], err = sp.take(ctx)
if err != nil {
t.Fatalf("failed to get session(%v): %v", i, err)
}
gotDs[shs[i].getID()] = true
}
if len(gotDs) != len(shs) {
t.Fatalf("session pool created %v sessions, want %v", len(gotDs), len(shs))
}
if wantDs := server.TestSpanner.DumpSessions(); !testEqual(gotDs, wantDs) {
t.Fatalf("session pool creates sessions %v, want %v", gotDs, wantDs)
}
// Verify that created sessions are recorded correctly in session pool.
sp.mu.Lock()
if int(sp.numOpened) != len(shs) {
t.Fatalf("session pool reports %v open sessions, want %v", sp.numOpened, len(shs))
}
if sp.createReqs != 0 {
t.Fatalf("session pool reports %v session create requests, want 0", int(sp.createReqs))
}
sp.mu.Unlock()
// Verify that created sessions are tracked correctly by healthcheck queue.
hc := sp.hc
hc.mu.Lock()
if hc.queue.Len() != len(shs) {
t.Fatalf("healthcheck queue length = %v, want %v", hc.queue.Len(), len(shs))
}
for _, s := range hc.queue.sessions {
if !gotDs[s.getID()] {
t.Fatalf("session %v is in healthcheck queue, but it is not created by session pool", s.getID())
}
}
hc.mu.Unlock()
}
// TestLIFOSessionOrder tests if session pool hand out sessions in LIFO order.
func TestLIFOSessionOrder(t *testing.T) {
t.Parallel()
ctx := context.Background()
_, client, teardown := setupMockedTestServerWithConfig(t,
ClientConfig{
SessionPoolConfig: SessionPoolConfig{
MaxOpened: 3,
MinOpened: 3,
},
})
defer teardown()
sp := client.idleSessions
// Create/take three sessions and recycle them.
shs, shsIDs := make([]*sessionHandle, 3), make([]string, 3)
for i := 0; i < len(shs); i++ {
var err error
if shs[i], err = sp.take(ctx); err != nil {
t.Fatalf("failed to take session(%v): %v", i, err)
}
shsIDs[i] = shs[i].getID()
}
for i := 0; i < len(shs); i++ {
shs[i].recycle()
}
for i := 2; i >= 0; i-- {
sh, err := sp.take(ctx)
if err != nil {
t.Fatalf("cannot take session from session pool: %v", err)
}
// check, if sessions returned in LIFO order.
if wantID, gotID := shsIDs[i], sh.getID(); wantID != gotID {
t.Fatalf("got session with id: %v, want: %v", gotID, wantID)
}
}
}
// TestLIFOTakeWriteSessionOrder tests if write session pool hand out sessions in LIFO order.
func TestLIFOTakeWriteSessionOrder(t *testing.T) {
t.Skip("https://github.com/googleapis/google-cloud-go/issues/1704")
t.Parallel()
ctx := context.Background()
_, client, teardown := setupMockedTestServerWithConfig(t,
ClientConfig{
SessionPoolConfig: SessionPoolConfig{
MaxOpened: 3,
MinOpened: 3,
WriteSessions: 1,
},
})
defer teardown()
sp := client.idleSessions
// Create/take three sessions and recycle them.
shs, shsIDs := make([]*sessionHandle, 3), make([]string, 3)
for i := 0; i < len(shs); i++ {
var err error
if shs[i], err = sp.takeWriteSession(ctx); err != nil {
t.Fatalf("failed to take session(%v): %v", i, err)
}
shsIDs[i] = shs[i].getID()
}
for i := 0; i < len(shs); i++ {
shs[i].recycle()
}
for i := 2; i >= 0; i-- {
ws, err := sp.takeWriteSession(ctx)
if err != nil {
t.Fatalf("cannot take session from session pool: %v", err)
}
// check, if write sessions returned in LIFO order.
if wantID, gotID := shsIDs[i], ws.getID(); wantID != gotID {
t.Fatalf("got session with id: %v, want: %v", gotID, wantID)
}
}
}
// TestTakeFromIdleList tests taking sessions from session pool's idle list.
func TestTakeFromIdleList(t *testing.T) {
t.Parallel()
ctx := context.Background()
// Make sure maintainer keeps the idle sessions.
server, client, teardown := setupMockedTestServerWithConfig(t,
ClientConfig{
SessionPoolConfig: SessionPoolConfig{MaxIdle: 10},
})
defer teardown()
sp := client.idleSessions
// Take ten sessions from session pool and recycle them.
shs := make([]*sessionHandle, 10)
for i := 0; i < len(shs); i++ {
var err error
shs[i], err = sp.take(ctx)
if err != nil {
t.Fatalf("failed to get session(%v): %v", i, err)
}
}
// Make sure it's sampled once before recycling, otherwise it will be
// cleaned up.
<-time.After(sp.SessionPoolConfig.healthCheckSampleInterval)
for i := 0; i < len(shs); i++ {
shs[i].recycle()
}
// Further session requests from session pool won't cause mockclient to
// create more sessions.
wantSessions := server.TestSpanner.DumpSessions()
// Take ten sessions from session pool again, this time all sessions should
// come from idle list.
gotSessions := map[string]bool{}
for i := 0; i < len(shs); i++ {
sh, err := sp.take(ctx)
if err != nil {
t.Fatalf("cannot take session from session pool: %v", err)
}
gotSessions[sh.getID()] = true
}
if len(gotSessions) != 10 {
t.Fatalf("got %v unique sessions, want 10", len(gotSessions))
}
if !testEqual(gotSessions, wantSessions) {
t.Fatalf("got sessions: %v, want %v", gotSessions, wantSessions)
}
}
// TesttakeWriteSessionFromIdleList tests taking write sessions from session
// pool's idle list.
func TestTakeWriteSessionFromIdleList(t *testing.T) {
t.Parallel()
ctx := context.Background()
// Make sure maintainer keeps the idle sessions.
server, client, teardown := setupMockedTestServerWithConfig(t,
ClientConfig{
SessionPoolConfig: SessionPoolConfig{MaxIdle: 20},
})
defer teardown()
sp := client.idleSessions
// Take ten sessions from session pool and recycle them.
shs := make([]*sessionHandle, 10)
for i := 0; i < len(shs); i++ {
var err error
shs[i], err = sp.takeWriteSession(ctx)
if err != nil {
t.Fatalf("failed to get session(%v): %v", i, err)
}
}
// Make sure it's sampled once before recycling, otherwise it will be
// cleaned up.
<-time.After(sp.SessionPoolConfig.healthCheckSampleInterval)
for i := 0; i < len(shs); i++ {
shs[i].recycle()
}
// Further session requests from session pool won't cause mockclient to
// create more sessions.
wantSessions := server.TestSpanner.DumpSessions()
// Take ten sessions from session pool again, this time all sessions should
// come from idle list.
gotSessions := map[string]bool{}
for i := 0; i < len(shs); i++ {
sh, err := sp.takeWriteSession(ctx)
if err != nil {
t.Fatalf("cannot take session from session pool: %v", err)
}
gotSessions[sh.getID()] = true
}
if len(gotSessions) != 10 {
t.Fatalf("got %v unique sessions, want 10", len(gotSessions))
}
if !testEqual(gotSessions, wantSessions) {
t.Fatalf("got sessions: %v, want %v", gotSessions, wantSessions)
}
}
// TestTakeFromIdleListChecked tests taking sessions from session pool's idle
// list, but with a extra ping check.
func TestTakeFromIdleListChecked(t *testing.T) {
t.Parallel()
ctx := context.Background()
// Make sure maintainer keeps the idle sessions.
server, client, teardown := setupMockedTestServerWithConfig(t,
ClientConfig{
SessionPoolConfig: SessionPoolConfig{
MaxIdle: 1,
HealthCheckInterval: 50 * time.Millisecond,
healthCheckSampleInterval: 10 * time.Millisecond,
},
})
defer teardown()
sp := client.idleSessions
// Stop healthcheck workers to simulate slow pings.
sp.hc.close()
// Create a session and recycle it.
sh, err := sp.take(ctx)
if err != nil {
t.Fatalf("failed to get session: %v", err)
}
// Force ping during the first take() by setting check time to the past.
sh.session.nextCheck = time.Now().Add(-time.Minute)
wantSid := sh.getID()
sh.recycle()
// Two back-to-back session requests, both of them should return the same
// session created before, but only the first of them should trigger a session ping.
for i := 0; i < 2; i++ {
// Take the session from the idle list and recycle it.
sh, err = sp.take(ctx)
if err != nil {
t.Fatalf("%v - failed to get session: %v", i, err)
}
if gotSid := sh.getID(); gotSid != wantSid {
t.Fatalf("%v - got session id: %v, want %v", i, gotSid, wantSid)
}
// The two back-to-back session requests shouldn't trigger any session
// pings because sessionPool.Take reschedules the next healthcheck.
if got, want := server.TestSpanner.DumpPings(), ([]string{wantSid}); !testEqual(got, want) {
t.Fatalf("%v - got ping session requests: %v, want %v", i, got, want)
}
sh.recycle()
}
// Inject session error to server stub, and take the session from the
// session pool, the old session should be destroyed and the session pool
// will create a new session.
server.TestSpanner.PutExecutionTime(MethodGetSession,
SimulatedExecutionTime{
Errors: []error{newSessionNotFoundError("projects/p/instances/i/databases/d/sessions/s")},
})
// Force ping by setting check time in the past.
s := sp.idleList.Front().Value.(*session)
s.nextCheck = time.Now().Add(-time.Minute)
// take will take the idle session. Then it will send a GetSession request
// to check if it's healthy. It'll discover that it's not healthy
// (NotFound), drop it, and create a new session.
sh, err = sp.take(ctx)
if err != nil {
t.Fatalf("failed to get session: %v", err)
}
ds := server.TestSpanner.DumpSessions()
if len(ds) != 1 {
t.Fatalf("dumped sessions from mockclient: %v, want %v", ds, sh.getID())
}
if sh.getID() == wantSid {
t.Fatalf("sessionPool.Take still returns the same session %v, want it to create a new one", wantSid)
}
}
// TestTakeFromIdleWriteListChecked tests taking sessions from session pool's
// idle list, but with a extra ping check.
func TestTakeFromIdleWriteListChecked(t *testing.T) {
t.Parallel()
ctx := context.Background()
// Make sure maintainer keeps the idle sessions.
server, client, teardown := setupMockedTestServerWithConfig(t,
ClientConfig{
SessionPoolConfig: SessionPoolConfig{
MaxIdle: 1,
HealthCheckInterval: 50 * time.Millisecond,
healthCheckSampleInterval: 10 * time.Millisecond,
},
})
defer teardown()
sp := client.idleSessions
// Stop healthcheck workers to simulate slow pings.
sp.hc.close()
// Create a session and recycle it.
sh, err := sp.takeWriteSession(ctx)
if err != nil {
t.Fatalf("failed to get session: %v", err)
}
wantSid := sh.getID()
// Set the next check in the past to ensure the next take() call will
// trigger a health check.
sh.session.nextCheck = time.Now().Add(-time.Minute)
sh.recycle()
// Two back-to-back session requests, both of them should return the same
// session created before and only the first of them should trigger a
// session ping.
for i := 0; i < 2; i++ {
// Take the session from the idle list and recycle it.
sh, err = sp.takeWriteSession(ctx)
if err != nil {
t.Fatalf("%v - failed to get session: %v", i, err)
}
if gotSid := sh.getID(); gotSid != wantSid {
t.Fatalf("%v - got session id: %v, want %v", i, gotSid, wantSid)
}
// The two back-to-back session requests shouldn't trigger any session
// pings because sessionPool.Take reschedules the next healthcheck.
if got, want := server.TestSpanner.DumpPings(), ([]string{wantSid}); !testEqual(got, want) {
t.Fatalf("%v - got ping session requests: %v, want %v", i, got, want)
}
sh.recycle()
}
// Inject session error to mockclient, and take the session from the
// session pool, the old session should be destroyed and the session pool
// will create a new session.
server.TestSpanner.PutExecutionTime(MethodGetSession,
SimulatedExecutionTime{
Errors: []error{newSessionNotFoundError("projects/p/instances/i/databases/d/sessions/s")},
})
// Force ping by setting check time in the past.
s := sp.idleList.Front().Value.(*session)
s.nextCheck = time.Now().Add(-time.Minute)
sh, err = sp.takeWriteSession(ctx)
if err != nil {
t.Fatalf("failed to get session: %v", err)
}
ds := server.TestSpanner.DumpSessions()
if len(ds) != 1 {
t.Fatalf("dumped sessions from mockclient: %v, want %v", ds, sh.getID())
}
if sh.getID() == wantSid {
t.Fatalf("sessionPool.Take still returns the same session %v, want it to create a new one", wantSid)
}
}
// TestSessionLeak tests leaking a session and getting the stack of the
// goroutine that leaked it.
func TestSessionLeak(t *testing.T) {
t.Parallel()
ctx := context.Background()
_, client, teardown := setupMockedTestServerWithConfig(t, ClientConfig{
SessionPoolConfig: SessionPoolConfig{
TrackSessionHandles: true,
MinOpened: 0,
MaxOpened: 1,
},
})
defer teardown()
// Execute a query without calling rowIterator.Stop. This will cause the
// session not to be returned to the pool.
single := client.Single()
iter := single.Query(ctx, NewStatement(SelectFooFromBar))
for {
_, err := iter.Next()
if err == iterator.Done {
break
}
if err != nil {
t.Fatalf("Got unexpected error while iterating results: %v\n", err)
}
}
// The session should not have been returned to the pool.
if g, w := client.idleSessions.idleList.Len(), 0; g != w {
t.Fatalf("Idle sessions count mismatch\nGot: %d\nWant: %d\n", g, w)
}
// The checked out session should contain a stack trace.
if single.sh.stack == nil {
t.Fatalf("Missing stacktrace from session handle")
}
stack := fmt.Sprintf("%s", single.sh.stack)
testMethod := "TestSessionLeak"
if !strings.Contains(stack, testMethod) {
t.Fatalf("Stacktrace does not contain '%s'\nGot: %s", testMethod, stack)
}
// Return the session to the pool.
iter.Stop()
// The stack should now have been removed from the session handle.
if single.sh.stack != nil {
t.Fatalf("Got unexpected stacktrace in session handle: %s", single.sh.stack)
}
// Do another query and hold on to the session.
single = client.Single()
iter = single.Query(ctx, NewStatement(SelectFooFromBar))
for {
_, err := iter.Next()
if err == iterator.Done {
break
}
if err != nil {
t.Fatalf("Got unexpected error while iterating results: %v\n", err)
}
}
// Try to do another query. This will fail as MaxOpened=1.
ctxWithTimeout, cancel := context.WithTimeout(ctx, time.Millisecond*10)
defer cancel()
single2 := client.Single()
iter2 := single2.Query(ctxWithTimeout, NewStatement(SelectFooFromBar))
_, gotErr := iter2.Next()
wantErr := client.idleSessions.errGetSessionTimeoutWithTrackedSessionHandles()
// The error should contain the stacktraces of all the checked out
// sessions.
if !testEqual(gotErr, wantErr) {
t.Fatalf("Error mismatch on iterating result set.\nGot: %v\nWant: %v\n", gotErr, wantErr)
}
if !strings.Contains(gotErr.Error(), testMethod) {
t.Fatalf("Error does not contain '%s'\nGot: %s", testMethod, gotErr.Error())
}
// Close iterators to check sessions back into the pool before closing.
iter2.Stop()
iter.Stop()
}
// TestMaxOpenedSessions tests max open sessions constraint.
func TestMaxOpenedSessions(t *testing.T) {
t.Parallel()
ctx := context.Background()
_, client, teardown := setupMockedTestServerWithConfig(t,
ClientConfig{
SessionPoolConfig: SessionPoolConfig{
MaxOpened: 1,
},
})
defer teardown()
sp := client.idleSessions
sh1, err := sp.take(ctx)
if err != nil {
t.Fatalf("cannot take session from session pool: %v", err)
}
// Session request will timeout due to the max open sessions constraint.
ctx2, cancel := context.WithTimeout(ctx, 10*time.Millisecond)
defer cancel()
_, gotErr := sp.take(ctx2)
if wantErr := sp.errGetBasicSessionTimeout(); !testEqual(gotErr, wantErr) {
t.Fatalf("the second session retrival returns error %v, want %v", gotErr, wantErr)
}
doneWaiting := make(chan struct{})
go func() {
// Destroy the first session to allow the next session request to
// proceed.
<-doneWaiting
sh1.destroy()
}()
go func() {
// Wait a short random time before destroying the session handle.
<-time.After(10 * time.Millisecond)
close(doneWaiting)
}()
// Now session request can be processed because the first session will be
// destroyed.
ctx3, cancel := context.WithTimeout(ctx, time.Second)
defer cancel()
sh2, err := sp.take(ctx3)
if err != nil {
t.Fatalf("after the first session is destroyed, session retrival still returns error %v, want nil", err)
}
if !sh2.session.isValid() || sh2.getID() == "" {
t.Fatalf("got invalid session: %v", sh2.session)
}
}
// TestMinOpenedSessions tests min open session constraint.
func TestMinOpenedSessions(t *testing.T) {
t.Parallel()
ctx := context.Background()
_, client, teardown := setupMockedTestServerWithConfig(t,
ClientConfig{
SessionPoolConfig: SessionPoolConfig{
MinOpened: 1,
healthCheckSampleInterval: time.Millisecond,
},
})
defer teardown()
sp := client.idleSessions
// Take ten sessions from session pool and recycle them.
var ss []*session
var shs []*sessionHandle
for i := 0; i < 10; i++ {
sh, err := sp.take(ctx)
if err != nil {
t.Fatalf("failed to get session(%v): %v", i, err)
}
ss = append(ss, sh.session)
shs = append(shs, sh)
sh.recycle()
}
for _, sh := range shs {
sh.recycle()
}
// Simulate session expiration.
for _, s := range ss {
s.destroy(true)
}
// Wait until the maintainer has had a chance to replenish the pool.
for i := 0; i < 10; i++ {
sp.mu.Lock()
if sp.numOpened > 0 {
sp.mu.Unlock()
break
}
sp.mu.Unlock()
<-time.After(sp.healthCheckSampleInterval)
}
sp.mu.Lock()
defer sp.mu.Unlock()
// There should be still one session left in either the idle list or in one
// of the other opened states due to the min open sessions constraint.
if (sp.idleList.Len() +
sp.idleWriteList.Len() +
int(sp.prepareReqs) +
int(sp.createReqs)) != 1 {
t.Fatalf(
"got %v sessions in idle lists, want 1. Opened: %d, read: %d, "+
"write: %d, in preparation: %d, in creation: %d",
sp.idleList.Len()+sp.idleWriteList.Len(), sp.numOpened,
sp.idleList.Len(), sp.idleWriteList.Len(), sp.prepareReqs,
sp.createReqs)
}
}
// TestMaxBurst tests max burst constraint.
func TestMaxBurst(t *testing.T) {
t.Parallel()
ctx := context.Background()
server, client, teardown := setupMockedTestServerWithConfig(t,
ClientConfig{
SessionPoolConfig: SessionPoolConfig{
MaxBurst: 1,
},
})
defer teardown()
sp := client.idleSessions
// Will cause session creation RPC to be retried forever.
server.TestSpanner.PutExecutionTime(MethodCreateSession,
SimulatedExecutionTime{
Errors: []error{status.Errorf(codes.Unavailable, "try later")},
KeepError: true,
})
// This session request will never finish until the injected error is
// cleared.
go sp.take(ctx)
// Poll for the execution of the first session request.
for {
sp.mu.Lock()
cr := sp.createReqs
sp.mu.Unlock()
if cr == 0 {
<-time.After(time.Second)
continue
}
// The first session request is being executed.
break
}
ctx2, cancel := context.WithTimeout(ctx, time.Second)
defer cancel()
_, gotErr := sp.take(ctx2)
// Since MaxBurst == 1, the second session request should block.
if wantErr := sp.errGetBasicSessionTimeout(); !testEqual(gotErr, wantErr) {
t.Fatalf("session retrival returns error %v, want %v", gotErr, wantErr)
}
// Let the first session request succeed.
server.TestSpanner.Freeze()
server.TestSpanner.PutExecutionTime(MethodCreateSession, SimulatedExecutionTime{})
//close(allowRequests)
server.TestSpanner.Unfreeze()
// Now new session request can proceed because the first session request will eventually succeed.
sh, err := sp.take(ctx)
if err != nil {
t.Fatalf("session retrival returns error %v, want nil", err)
}
if !sh.session.isValid() || sh.getID() == "" {
t.Fatalf("got invalid session: %v", sh.session)
}
}
// TestSessionRecycle tests recycling sessions.
func TestSessionRecycle(t *testing.T) {
t.Parallel()
ctx := context.Background()
// Set MaxBurst=MinOpened to prevent additional sessions to be created
// while session pool initialization is still running.
_, client, teardown := setupMockedTestServerWithConfig(t,
ClientConfig{
SessionPoolConfig: SessionPoolConfig{
MinOpened: 1,
MaxIdle: 5,
MaxBurst: 1,
},
})
defer teardown()
sp := client.idleSessions
// Test session is correctly recycled and reused.
for i := 0; i < 20; i++ {
s, err := sp.take(ctx)
if err != nil {
t.Fatalf("cannot get the session %v: %v", i, err)
}
s.recycle()
}
sp.mu.Lock()
defer sp.mu.Unlock()
// The session pool should only contain 1 session, as there is no minimum
// configured. In addition, there has never been more than one session in
// use at any time, so there's no need for the session pool to create a
// second session. The session has also been in use all the time, so there
// also no reason for the session pool to delete the session.
if sp.numOpened != 1 {
t.Fatalf("Expect session pool size 1, got %d", sp.numOpened)
}
}
// TestSessionDestroy tests destroying sessions.
func TestSessionDestroy(t *testing.T) {
t.Parallel()
ctx := context.Background()
_, client, teardown := setupMockedTestServerWithConfig(t,
ClientConfig{
SessionPoolConfig: SessionPoolConfig{
MinOpened: 1,
MaxBurst: 1,
},
})
defer teardown()
sp := client.idleSessions
// Creating a session pool with MinSessions=1 will automatically start the
// creation of 1 session when the session pool is created. As MaxBurst=1,
// the session pool will never create more than 1 session at a time, so the
// take() method will wait if the initial session has not yet been created.
sh, err := sp.take(ctx)
if err != nil {
t.Fatalf("cannot get session from session pool: %v", err)
}
s := sh.session
sh.recycle()
if d := s.destroy(true); d || !s.isValid() {
// Session should be remaining because of min open sessions constraint.
t.Fatalf("session %s invalid, want it to stay alive. (destroy in expiration mode, success: %v)", s.id, d)
}
if d := s.destroy(false); !d || s.isValid() {
// Session should be destroyed.
t.Fatalf("failed to destroy session %s. (destroy in default mode, success: %v)", s.id, d)
}
}
// TestHcHeap tests heap operation on top of hcHeap.
func TestHcHeap(t *testing.T) {
in := []*session{
{nextCheck: time.Unix(10, 0)},
{nextCheck: time.Unix(0, 5)},
{nextCheck: time.Unix(1, 8)},
{nextCheck: time.Unix(11, 7)},
{nextCheck: time.Unix(6, 3)},
}
want := []*session{
{nextCheck: time.Unix(1, 8), hcIndex: 0},
{nextCheck: time.Unix(6, 3), hcIndex: 1},
{nextCheck: time.Unix(8, 2), hcIndex: 2},
{nextCheck: time.Unix(10, 0), hcIndex: 3},
{nextCheck: time.Unix(11, 7), hcIndex: 4},
}
hh := hcHeap{}
for _, s := range in {
heap.Push(&hh, s)
}
// Change top of the heap and do a adjustment.
hh.sessions[0].nextCheck = time.Unix(8, 2)
heap.Fix(&hh, 0)
for idx := 0; hh.Len() > 0; idx++ {
got := heap.Pop(&hh).(*session)
want[idx].hcIndex = -1
if !testEqual(got, want[idx]) {
t.Fatalf("%v: heap.Pop returns %v, want %v", idx, got, want[idx])
}
}
}
// TestHealthCheckScheduler tests if healthcheck workers can schedule and
// perform healthchecks properly.
func TestHealthCheckScheduler(t *testing.T) {
t.Parallel()
ctx := context.Background()
server, client, teardown := setupMockedTestServerWithConfig(t,
ClientConfig{
SessionPoolConfig: SessionPoolConfig{
HealthCheckInterval: 50 * time.Millisecond,
healthCheckSampleInterval: 10 * time.Millisecond,
},
})
defer teardown()
sp := client.idleSessions
// Create 50 sessions.
for i := 0; i < 50; i++ {
_, err := sp.take(ctx)
if err != nil {
t.Fatalf("cannot get session from session pool: %v", err)
}
}
// Make sure we start with a ping history to avoid that the first
// sessions that were created have not already exceeded the maximum
// number of pings.
server.TestSpanner.ClearPings()
// Wait for 10-30 pings per session.
waitFor(t, func() error {
// Only check actually live sessions and ignore any sessions the
// session pool may have deleted in the meantime.
liveSessions := server.TestSpanner.DumpSessions()
dp := server.TestSpanner.DumpPings()
gotPings := map[string]int64{}
for _, p := range dp {
gotPings[p]++
}
for s := range liveSessions {
want := int64(20)
if got := gotPings[s]; got < want/2 || got > want+want/2 {
// This is an unnacceptable amount of pings.
return fmt.Errorf("got %v healthchecks on session %v, want it between (%v, %v)", got, s, want/2, want+want/2)
}
}
return nil
})
}
// TestHealthCheck_FirstHealthCheck tests if the first healthcheck scheduling
// works properly.
func TestHealthCheck_FirstHealthCheck(t *testing.T) {
t.Parallel()
_, client, teardown := setupMockedTestServerWithConfig(t,
ClientConfig{
SessionPoolConfig: SessionPoolConfig{
MaxOpened: 0,
MinOpened: 0,
HealthCheckInterval: 50 * time.Minute,
},
})
defer teardown()
sp := client.idleSessions
now := time.Now()
start := now.Add(time.Duration(float64(sp.hc.interval) * 0.2))
// A second is added to avoid the edge case.
end := now.Add(time.Duration(float64(sp.hc.interval)*1.1) + time.Second)
s := &session{}
sp.hc.scheduledHCLocked(s)
if s.nextCheck.Before(start) || s.nextCheck.After(end) {
t.Fatalf("The first healthcheck schedule is not in the correct range: %v", s.nextCheck)
}
if !s.firstHCDone {
t.Fatal("The flag 'firstHCDone' should be set to true after the first healthcheck.")
}
}
// TestHealthCheck_NonFirstHealthCheck tests if the scheduling after the first
// health check works properly.
func TestHealthCheck_NonFirstHealthCheck(t *testing.T) {
t.Parallel()
_, client, teardown := setupMockedTestServerWithConfig(t,
ClientConfig{
SessionPoolConfig: SessionPoolConfig{
MaxOpened: 0,
MinOpened: 0,
HealthCheckInterval: 50 * time.Minute,
},
})
defer teardown()
sp := client.idleSessions
now := time.Now()
start := now.Add(time.Duration(float64(sp.hc.interval) * 0.9))
// A second is added to avoid the edge case.
end := now.Add(time.Duration(float64(sp.hc.interval)*1.1) + time.Second)
s := &session{firstHCDone: true}
sp.hc.scheduledHCLocked(s)
if s.nextCheck.Before(start) || s.nextCheck.After(end) {
t.Fatalf("The non-first healthcheck schedule is not in the correct range: %v", s.nextCheck)
}
}
// Tests that a fractions of sessions are prepared for write by health checker.
func TestWriteSessionsPrepared(t *testing.T) {
t.Parallel()
ctx := context.Background()
_, client, teardown := setupMockedTestServerWithConfig(t,
ClientConfig{
SessionPoolConfig: SessionPoolConfig{
WriteSessions: 0.5,
MaxIdle: 20,
HealthCheckInterval: time.Nanosecond,
},
})
defer teardown()
sp := client.idleSessions
shs := make([]*sessionHandle, 10)
var err error
for i := 0; i < 10; i++ {
shs[i], err = sp.take(ctx)
if err != nil {
t.Fatalf("cannot get session from session pool: %v", err)
}
}
// Now there are 10 sessions in the pool. Release them.
for _, sh := range shs {
sh.recycle()
}
// Take 5 write sessions. The write sessions will be taken from either the
// list of prepared sessions (idleWriteList), or they will be prepared
// during the takeWriteSession method.
wshs := make([]*sessionHandle, 5)
for i := 0; i < 5; i++ {
wshs[i], err = sp.takeWriteSession(ctx)
if err != nil {
t.Fatalf("cannot get session from session pool: %v", err)
}
if wshs[i].getTransactionID() == nil {
t.Fatalf("got nil transaction id from session pool")
}
}
// Return the session to the pool.
for _, sh := range wshs {
sh.recycle()
}
// Now force creation of 10 more sessions.
shs = make([]*sessionHandle, 20)
for i := 0; i < 20; i++ {
shs[i], err = sp.take(ctx)
if err != nil {
t.Fatalf("cannot get session from session pool: %v", err)
}
}
// Now there are 20 sessions in the pool. Release them.
for _, sh := range shs {
sh.recycle()
}
// The health checker should eventually prepare 10 of the 20 sessions with
// a r/w tx.
waitUntil := time.After(time.Second)
var numWritePrepared int
for numWritePrepared < 10 {
select {
case <-waitUntil:
break
default:
}
sp.mu.Lock()
numWritePrepared = sp.idleWriteList.Len()
sp.mu.Unlock()
}
sp.mu.Lock()
defer sp.mu.Unlock()
if sp.idleWriteList.Len() != 10 {
t.Fatalf("Expect 10 write prepared session, got: %d", sp.idleWriteList.Len())
}
}
// TestTakeFromWriteQueue tests that sessionPool.take() returns write prepared
// sessions as well.
func TestTakeFromWriteQueue(t *testing.T) {
t.Parallel()
ctx := context.Background()
_, client, teardown := setupMockedTestServerWithConfig(t,
ClientConfig{
SessionPoolConfig: SessionPoolConfig{
MaxOpened: 1,
WriteSessions: 1.0,
MaxIdle: 1,
HealthCheckInterval: time.Nanosecond,
},
})
defer teardown()
sp := client.idleSessions
sh, err := sp.take(ctx)
if err != nil {
t.Fatalf("cannot get session from session pool: %v", err)
}
sh.recycle()
// Wait until the health checker has write-prepared the session.
waitUntil := time.After(time.Second)
var numWritePrepared int
for numWritePrepared == 0 {
select {
case <-waitUntil:
break
default:
}
sp.mu.Lock()
numWritePrepared = sp.idleWriteList.Len()
sp.mu.Unlock()
}
// The session should now be in write queue but take should also return it.
sp.mu.Lock()
if sp.idleWriteList.Len() == 0 {
t.Fatalf("write queue unexpectedly empty")
}
if sp.idleList.Len() != 0 {
t.Fatalf("read queue not empty")
}
sp.mu.Unlock()
sh, err = sp.take(ctx)
if err != nil {
t.Fatalf("cannot get session from session pool: %v", err)
}
sh.recycle()
}
// The session pool should stop trying to create write-prepared sessions if a
// non-transient error occurs while trying to begin a transaction. The
// process for preparing write sessions should automatically be re-enabled if
// a BeginTransaction call initiated by takeWriteSession succeeds.
//
// The only exception to the above is that a 'Session not found' error should
// cause the session to be removed from the session pool, and it should not
// affect the background process of preparing sessions.
func TestErrorOnPrepareSession(t *testing.T) {
t.Parallel()
serverErrors := []error{
status.Errorf(codes.PermissionDenied, "Caller is missing IAM permission spanner.databases.beginOrRollbackReadWriteTransaction on resource"),
status.Errorf(codes.NotFound, `Database not found: projects/<project>/instances/<instance>/databases/<database> resource_type: "type.googleapis.com/google.spanner.admin.database.v1.Database" resource_name: "projects/<project>/instances/<instance>/databases/<database>" description: "Database does not exist."`),
status.Errorf(codes.FailedPrecondition, "Invalid transaction option"),
status.Errorf(codes.Internal, "Unknown server error"),
}
logger := log.New(os.Stderr, "", log.LstdFlags)
for _, serverErr := range serverErrors {
ctx := context.Background()
server, client, teardown := setupMockedTestServerWithConfig(t,
ClientConfig{
SessionPoolConfig: SessionPoolConfig{
MinOpened: 10,
MaxOpened: 10,
WriteSessions: 0.5,
HealthCheckInterval: time.Millisecond,
},
logger: logger,
})
defer teardown()
// Discard logging until trying to prepare sessions has stopped.
logger.SetOutput(ioutil.Discard)
server.TestSpanner.PutExecutionTime(MethodBeginTransaction, SimulatedExecutionTime{
Errors: []error{serverErr},
KeepError: true,
})
sp := client.idleSessions
// Wait until the health checker has tried to write-prepare a session.
// This will cause the session pool to write some errors to the log that
// preparing sessions failed.
waitUntil := time.After(time.Second)
var prepareDisabled bool
var numOpened int
waitForPrepare:
for !prepareDisabled || numOpened < 10 {
select {
case <-waitUntil:
break waitForPrepare
default:
}
sp.mu.Lock()
prepareDisabled = sp.disableBackgroundPrepareSessions
numOpened = sp.idleList.Len()
sp.mu.Unlock()
}
// Re-enable logging.
logger.SetOutput(os.Stderr)
// There should be no write-prepared sessions.
sp.mu.Lock()
if sp.idleWriteList.Len() != 0 {
sp.mu.Unlock()
t.Fatalf("write queue unexpectedly not empty")
}
// All sessions should be in the read idle list.
if g, w := sp.idleList.Len(), 10; g != w {
sp.mu.Unlock()
t.Fatalf("session count mismatch:\nWant: %v\nGot: %v", w, g)
}
sp.mu.Unlock()
// Take a read session should succeed.
sh, err := sp.take(ctx)
if err != nil {
t.Fatalf("cannot get session from session pool: %v", err)
}
sh.recycle()
// Take a write session should fail with the server error.
_, err = sp.takeWriteSession(ctx)
if ErrCode(err) != ErrCode(serverErr) {
t.Fatalf("take write session failed with unexpected error.\nGot: %v\nWant: %v\n", err, serverErr)
}
// Clearing the error on the server should allow us to take a write
// session.
server.TestSpanner.PutExecutionTime(MethodBeginTransaction, SimulatedExecutionTime{})
sh, err = sp.takeWriteSession(ctx)
if err != nil {
t.Fatalf("cannot get write session from session pool: %v", err)
}
sh.recycle()
// The maintainer should also pick this up and prepare 50% of the sessions.
waitUntil = time.After(time.Second)
var numPrepared int
for numPrepared < 5 {
select {
case <-waitUntil:
break
default:
}
sp.mu.Lock()
numPrepared = sp.idleWriteList.Len()
sp.mu.Unlock()
}
sp.mu.Lock()
if g, w := sp.idleWriteList.Len(), 5; g != w {
sp.mu.Unlock()
t.Fatalf("write session count mismatch:\nWant: %v\nGot: %v", w, g)
}
sp.mu.Unlock()
}
}
// The session pool should continue to try to create write-prepared sessions if
// a 'Session not found' error occurs. The session that has been deleted by
// backend should be removed from the pool, and the maintainer should create a
// new session if this causes the number of sessions in the pool to fall below
// MinOpened.
func TestSessionNotFoundOnPrepareSession(t *testing.T) {
t.Parallel()
// The server will return 'Session not found' for the first 8
// BeginTransaction calls.
sessionNotFoundErr := newSessionNotFoundError("projects/p/instances/i/databases/d/sessions/s")
serverErrors := make([]error, 8)
for i := range serverErrors {
serverErrors[i] = sessionNotFoundErr
}
ctx := context.Background()
logger := log.New(os.Stderr, "", log.LstdFlags)
server, client, teardown := setupMockedTestServerWithConfig(t,
ClientConfig{
SessionPoolConfig: SessionPoolConfig{
MinOpened: 10,
MaxOpened: 10,
WriteSessions: 0.5,
HealthCheckInterval: time.Millisecond,
healthCheckSampleInterval: time.Millisecond,
},
logger: logger,
})
defer teardown()
// Discard logging until trying to prepare sessions has stopped.
logger.SetOutput(ioutil.Discard)
server.TestSpanner.PutExecutionTime(MethodBeginTransaction, SimulatedExecutionTime{
Errors: serverErrors,
})
sp := client.idleSessions
// Wait until the health checker has tried to write-prepare the sessions.
waitUntil := time.After(5 * time.Second)
var numWriteSessions int
var numReadSessions int
waitForPrepare:
for (numWriteSessions+numReadSessions) < 10 || numWriteSessions < 5 {
select {
case <-waitUntil:
break waitForPrepare
default:
}
sp.mu.Lock()
numReadSessions = sp.idleList.Len()
numWriteSessions = sp.idleWriteList.Len()
sp.mu.Unlock()
}
// Re-enable logging.
logger.SetOutput(os.Stderr)
// There should be at least 5 write-prepared sessions.
sp.mu.Lock()
if g, w := sp.idleWriteList.Len(), 5; g < w {
sp.mu.Unlock()
t.Fatalf("write-prepared session count mismatch.\nWant at least: %v\nGot: %v", w, g)
}
// The other sessions should be in the read idle list.
if g, w := sp.idleList.Len()+sp.idleWriteList.Len(), 10; g != w {
sp.mu.Unlock()
t.Fatalf("total session count mismatch:\nWant: %v\nGot: %v", w, g)
}
sp.mu.Unlock()
// Take a read session should succeed.
sh, err := sp.take(ctx)
if err != nil {
t.Fatalf("cannot get session from session pool: %v", err)
}
sh.recycle()
// Take a write session should succeed.
sh, err = sp.takeWriteSession(ctx)
if err != nil {
t.Fatalf("take write session failed with unexpected error.\nGot: %v\nWant: %v\n", err, nil)
}
sh.recycle()
}
// TestSessionHealthCheck tests healthchecking cases.
func TestSessionHealthCheck(t *testing.T) {
t.Parallel()
ctx := context.Background()
server, client, teardown := setupMockedTestServerWithConfig(t,
ClientConfig{
SessionPoolConfig: SessionPoolConfig{
HealthCheckInterval: time.Nanosecond,
healthCheckSampleInterval: 10 * time.Millisecond,
},
})
defer teardown()
sp := client.idleSessions
// Test pinging sessions.
sh, err := sp.take(ctx)
if err != nil {
t.Fatalf("cannot get session from session pool: %v", err)
}
// Wait for healthchecker to send pings to session.
waitFor(t, func() error {
pings := server.TestSpanner.DumpPings()
if len(pings) == 0 || pings[0] != sh.getID() {
return fmt.Errorf("healthchecker didn't send any ping to session %v", sh.getID())
}
return nil
})
// Test broken session detection.
sh, err = sp.take(ctx)
if err != nil {
t.Fatalf("cannot get session from session pool: %v", err)
}
server.TestSpanner.Freeze()
server.TestSpanner.PutExecutionTime(MethodGetSession,
SimulatedExecutionTime{
Errors: []error{newSessionNotFoundError("projects/p/instances/i/databases/d/sessions/s")},
KeepError: true,
})
server.TestSpanner.Unfreeze()
s := sh.session
waitFor(t, func() error {
if sh.session.isValid() {
return fmt.Errorf("session(%v) is still alive, want it to be dropped by healthcheck workers", s)
}
return nil
})
server.TestSpanner.Freeze()
server.TestSpanner.PutExecutionTime(MethodGetSession, SimulatedExecutionTime{})
server.TestSpanner.Unfreeze()
// Test garbage collection.
sh, err = sp.take(ctx)
if err != nil {
t.Fatalf("cannot get session from session pool: %v", err)
}
sp.close()
if sh.session.isValid() {
t.Fatalf("session(%v) is still alive, want it to be garbage collected", s)
}
}
// TestStressSessionPool does stress test on session pool by the following concurrent operations:
// 1) Test worker gets a session from the pool.
// 2) Test worker turns a session back into the pool.
// 3) Test worker destroys a session got from the pool.
// 4) Healthcheck destroys a broken session (because a worker has already destroyed it).
// 5) Test worker closes the session pool.
//
// During the test, the session pool maintainer maintains the number of sessions,
// and it is expected that all sessions that are taken from session pool remains valid.
// When all test workers and healthcheck workers exit, mockclient, session pool
// and healthchecker should be in consistent state.
func TestStressSessionPool(t *testing.T) {
t.Parallel()
// Use concurrent workers to test different session pool built from different configurations.
for ti, cfg := range []SessionPoolConfig{
{},
{MinOpened: 10, MaxOpened: 100},
{MaxBurst: 50},
{MinOpened: 10, MaxOpened: 200, MaxBurst: 5},
{MinOpened: 10, MaxOpened: 200, MaxBurst: 5, WriteSessions: 0.2},
} {
// Create a more aggressive session healthchecker to increase test concurrency.
cfg.HealthCheckInterval = 50 * time.Millisecond
cfg.healthCheckSampleInterval = 10 * time.Millisecond
cfg.HealthCheckWorkers = 50
server, client, teardown := setupMockedTestServerWithConfig(t, ClientConfig{
SessionPoolConfig: cfg,
})
sp := client.idleSessions
// Create a test group for this configuration and schedule 100 sub
// sub tests within the group.
t.Run(fmt.Sprintf("TestStressSessionPoolGroup%v", ti), func(t *testing.T) {
for i := 0; i < 100; i++ {
idx := i
t.Logf("TestStressSessionPoolWithCfg%dWorker%03d", ti, idx)
testStressSessionPool(t, cfg, ti, idx, sp, client)
}
})
sp.hc.close()
// Here the states of healthchecker, session pool and mockclient are
// stable.
sp.mu.Lock()
idleSessions := map[string]bool{}
hcSessions := map[string]bool{}
mockSessions := server.TestSpanner.DumpSessions()
// Dump session pool's idle list.
for sl := sp.idleList.Front(); sl != nil; sl = sl.Next() {
s := sl.Value.(*session)
if idleSessions[s.getID()] {
t.Fatalf("%v: found duplicated session in idle list: %v", ti, s.getID())
}
idleSessions[s.getID()] = true
}
for sl := sp.idleWriteList.Front(); sl != nil; sl = sl.Next() {
s := sl.Value.(*session)
if idleSessions[s.getID()] {
t.Fatalf("%v: found duplicated session in idle write list: %v", ti, s.getID())
}
idleSessions[s.getID()] = true
}
if int(sp.numOpened) != len(idleSessions) {
t.Fatalf("%v: number of opened sessions (%v) != number of idle sessions (%v)", ti, sp.numOpened, len(idleSessions))
}
if sp.createReqs != 0 {
t.Fatalf("%v: number of pending session creations = %v, want 0", ti, sp.createReqs)
}
// Dump healthcheck queue.
for _, s := range sp.hc.queue.sessions {
if hcSessions[s.getID()] {
t.Fatalf("%v: found duplicated session in healthcheck queue: %v", ti, s.getID())
}
hcSessions[s.getID()] = true
}
sp.mu.Unlock()
// Verify that idleSessions == hcSessions == mockSessions.
if !testEqual(idleSessions, hcSessions) {
t.Fatalf("%v: sessions in idle list (%v) != sessions in healthcheck queue (%v)", ti, idleSessions, hcSessions)
}
// The server may contain more sessions than the health check queue.
// This can be caused by a timeout client side during a CreateSession
// request. The request may still be received and executed by the
// server, but the session pool will not register the session.
for id, b := range hcSessions {
if b && !mockSessions[id] {
t.Fatalf("%v: session in healthcheck queue (%v) was not found on server", ti, id)
}
}
sp.close()
mockSessions = server.TestSpanner.DumpSessions()
for id, b := range hcSessions {
if b && mockSessions[id] {
t.Fatalf("Found session from pool still live on server: %v", id)
}
}
teardown()
}
}
func testStressSessionPool(t *testing.T, cfg SessionPoolConfig, ti int, idx int, pool *sessionPool, client *Client) {
ctx := context.Background()
// Test worker iterates 1K times and tries different
// session / session pool operations.
for j := 0; j < 1000; j++ {
if idx%10 == 0 && j >= 900 {
// Close the pool in selected set of workers during the
// middle of the test.
pool.close()
}
// Take a write sessions ~ 20% of the times.
takeWrite := rand.Intn(5) == 4
var (
sh *sessionHandle
gotErr error
)
wasValid := pool.isValid()
if takeWrite {
sh, gotErr = pool.takeWriteSession(ctx)
} else {
sh, gotErr = pool.take(ctx)
}
if gotErr != nil {
if pool.isValid() {
t.Fatalf("%v.%v: pool.take returns error when pool is still valid: %v", ti, idx, gotErr)
}
// If the session pool was closed when we tried to take a session
// from the pool, then we should have gotten a specific error.
// If the session pool was closed between the take() and now (or
// even during a take()) then an error is ok.
if !wasValid {
if wantErr := errInvalidSessionPool; gotErr != wantErr {
t.Fatalf("%v.%v: got error when pool is closed: %v, want %v", ti, idx, gotErr, wantErr)
}
}
continue
}
// Verify if session is valid when session pool is valid.
// Note that if session pool is invalid after sh is taken,
// then sh might be invalidated by healthcheck workers.
if (sh.getID() == "" || sh.session == nil || !sh.session.isValid()) && pool.isValid() {
t.Fatalf("%v.%v.%v: pool.take returns invalid session %v", ti, idx, takeWrite, sh.session)
}
if takeWrite && sh.getTransactionID() == nil {
t.Fatalf("%v.%v: pool.takeWriteSession returns session %v without transaction", ti, idx, sh.session)
}
if rand.Intn(100) < idx {
// Random sleep before destroying/recycling the session,
// to give healthcheck worker a chance to step in.
<-time.After(time.Duration(rand.Int63n(int64(cfg.HealthCheckInterval))))
}
if rand.Intn(100) < idx {
// destroy the session.
sh.destroy()
continue
}
// recycle the session.
sh.recycle()
}
}
// TestMaintainer checks the session pool maintainer maintains the number of
// sessions in the following cases:
//
// 1. On initialization of session pool, replenish session pool to meet
// MinOpened or MaxIdle.
// 2. On increased session usage, provision extra MaxIdle sessions.
// 3. After the surge passes, scale down the session pool accordingly.
func TestMaintainer(t *testing.T) {
t.Parallel()
ctx := context.Background()
minOpened := uint64(5)
maxIdle := uint64(4)
_, client, teardown := setupMockedTestServerWithConfig(t,
ClientConfig{
SessionPoolConfig: SessionPoolConfig{
MinOpened: minOpened,
MaxIdle: maxIdle,
healthCheckSampleInterval: time.Millisecond,
},
})
defer teardown()
sp := client.idleSessions
waitFor(t, func() error {
sp.mu.Lock()
defer sp.mu.Unlock()
if sp.numOpened != 5 {
return fmt.Errorf("Replenish. Expect %d open, got %d", sp.MinOpened, sp.numOpened)
}
return nil
})
// To save test time, we are not creating many sessions, because the time
// to create sessions will have impact on the decision on sessionsToKeep.
// We also parallelize the take and recycle process.
shs := make([]*sessionHandle, 20)
for i := 0; i < len(shs); i++ {
var err error
shs[i], err = sp.take(ctx)
if err != nil {
t.Fatalf("cannot get session from session pool: %v", err)
}
}
sp.mu.Lock()
if sp.numOpened != 20 {
t.Fatalf("Scale out from normal use. Expect %d open, got %d", 20, sp.numOpened)
}
sp.mu.Unlock()
// Return 14 sessions to the pool. There are still 6 sessions checked out.
for _, sh := range shs[:14] {
sh.recycle()
}
// The pool should scale down to sessionsInUse + MaxIdle = 6 + 4 = 10.
waitFor(t, func() error {
sp.mu.Lock()
defer sp.mu.Unlock()
if sp.numOpened != 10 {
return fmt.Errorf("Keep extra MaxIdle sessions. Expect %d open, got %d", 10, sp.numOpened)
}
return nil
})
// Return the remaining 6 sessions.
// The pool should now scale down to minOpened + maxIdle.
for _, sh := range shs[14:] {
sh.recycle()
}
waitFor(t, func() error {
sp.mu.Lock()
defer sp.mu.Unlock()
if sp.numOpened != minOpened {
return fmt.Errorf("Scale down. Expect %d open, got %d", minOpened+maxIdle, sp.numOpened)
}
return nil
})
}
// Tests that the session pool creates up to MinOpened connections.
//
// Historical context: This test also checks that a low
// healthCheckSampleInterval does not prevent it from opening connections.
// The low healthCheckSampleInterval will however sometimes cause session
// creations to time out. That should not be considered a problem, but it
// could cause the test case to fail if it happens too often.
// See: https://github.com/googleapis/google-cloud-go/issues/1259
func TestInit_CreatesSessions(t *testing.T) {
t.Parallel()
spc := SessionPoolConfig{
MinOpened: 10,
MaxIdle: 10,
WriteSessions: 0.0,
healthCheckSampleInterval: 20 * time.Millisecond,
}
server, client, teardown := setupMockedTestServerWithConfig(t,
ClientConfig{
SessionPoolConfig: spc,
NumChannels: 4,
})
defer teardown()
sp := client.idleSessions
timeout := time.After(4 * time.Second)
var numOpened int
loop:
for {
select {
case <-timeout:
t.Fatalf("timed out, got %d session(s), want %d", numOpened, spc.MinOpened)
default:
sp.mu.Lock()
numOpened = sp.idleList.Len() + sp.idleWriteList.Len()
sp.mu.Unlock()
if numOpened == 10 {
break loop
}
}
}
_, err := shouldHaveReceived(server.TestSpanner, []interface{}{
&sppb.BatchCreateSessionsRequest{},
&sppb.BatchCreateSessionsRequest{},
&sppb.BatchCreateSessionsRequest{},
&sppb.BatchCreateSessionsRequest{},
})
if err != nil {
t.Fatal(err)
}
}
// Tests that the session pool with a MinSessions>0 also prepares WriteSessions
// sessions.
func TestInit_PreparesSessions(t *testing.T) {
t.Parallel()
spc := SessionPoolConfig{
MinOpened: 10,
MaxIdle: 10,
WriteSessions: 0.5,
healthCheckSampleInterval: 20 * time.Millisecond,
}
_, client, teardown := setupMockedTestServerWithConfig(t,
ClientConfig{
SessionPoolConfig: spc,
})
defer teardown()
sp := client.idleSessions
timeoutAmt := 4 * time.Second
timeout := time.After(timeoutAmt)
var numPrepared int
want := int(spc.WriteSessions * float64(spc.MinOpened))
loop:
for {
select {
case <-timeout:
t.Fatalf("timed out after %v, got %d write-prepared session(s), want %d", timeoutAmt, numPrepared, want)
default:
sp.mu.Lock()
numPrepared = sp.idleWriteList.Len()
sp.mu.Unlock()
if numPrepared == want {
break loop
}
}
}
}
func (s1 *session) Equal(s2 *session) bool {
return s1.client == s2.client &&
s1.id == s2.id &&
s1.pool == s2.pool &&
s1.createTime == s2.createTime &&
s1.valid == s2.valid &&
s1.hcIndex == s2.hcIndex &&
s1.idleList == s2.idleList &&
s1.nextCheck.Equal(s2.nextCheck) &&
s1.checkingHealth == s2.checkingHealth &&
testEqual(s1.md, s2.md) &&
bytes.Equal(s1.tx, s2.tx)
}
func waitFor(t *testing.T, assert func() error) {
t.Helper()
timeout := 15 * time.Second
ta := time.After(timeout)
for {
select {
case <-ta:
if err := assert(); err != nil {
t.Fatalf("after %v waiting, got %v", timeout, err)
}
return
default:
}
if err := assert(); err != nil {
// Fail. Let's pause and retry.
time.Sleep(10 * time.Millisecond)
continue
}
return
}
}
// Tests that maintainer only deletes sessions after a full maintenance window
// of 10 cycles has finished.
func TestMaintainer_DeletesSessions(t *testing.T) {
t.Parallel()
ctx := context.Background()
const sampleInterval = time.Millisecond * 10
_, client, teardown := setupMockedTestServerWithConfig(t,
ClientConfig{
SessionPoolConfig: SessionPoolConfig{healthCheckSampleInterval: sampleInterval},
})
defer teardown()
sp := client.idleSessions
// Take two sessions from the pool.
// This will cause max sessions in use to be 2 during this window.
sh1 := takeSession(ctx, t, sp)
sh2 := takeSession(ctx, t, sp)
wantSessions := map[string]bool{}
wantSessions[sh1.getID()] = true
wantSessions[sh2.getID()] = true
// Return the sessions to the pool and then assure that they
// are not deleted while still within the maintenance window.
sh1.recycle()
sh2.recycle()
// Wait for 20 milliseconds, i.e. approx 2 iterations of the
// maintainer. The sessions should still be in the pool.
<-time.After(sampleInterval * 2)
sh3 := takeSession(ctx, t, sp)
sh4 := takeSession(ctx, t, sp)
// Check that the returned sessions are equal to the sessions that we got
// the first time from the session pool.
gotSessions := map[string]bool{}
gotSessions[sh3.getID()] = true
gotSessions[sh4.getID()] = true
testEqual(wantSessions, gotSessions)
// Return the sessions to the pool.
sh3.recycle()
sh4.recycle()
// Now wait for the maintenance window to finish. This will cause the
// maintainer to enter a new window and reset the max number of sessions in
// use to the currently number of checked out sessions. That is 0, as all
// sessions have been returned to the pool. That again will cause the
// maintainer to delete these sessions at the next iteration, unless we
// checkout new sessions during the first iteration.
waitFor(t, func() error {
sp.mu.Lock()
defer sp.mu.Unlock()
if sp.numOpened > 0 {
return fmt.Errorf("session pool still contains more than 0 sessions")
}
return nil
})
sh5 := takeSession(ctx, t, sp)
sh6 := takeSession(ctx, t, sp)
// Assure that these sessions are new sessions.
if gotSessions[sh5.getID()] || gotSessions[sh6.getID()] {
t.Fatal("got unexpected existing session from pool")
}
}
func takeSession(ctx context.Context, t *testing.T, sp *sessionPool) *sessionHandle {
sh, err := sp.take(ctx)
if err != nil {
t.Fatalf("cannot get session from session pool: %v", err)
}
return sh
}
func TestMaintenanceWindow_CycleAndUpdateMaxCheckedOut(t *testing.T) {
t.Parallel()
maxOpened := uint64(1000)
mw := newMaintenanceWindow(maxOpened)
for _, m := range mw.maxSessionsCheckedOut {
if m < maxOpened {
t.Fatalf("Max sessions checked out mismatch.\nGot: %v\nWant: %v", m, maxOpened)
}
}
// Do one cycle and simulate that there are currently no sessions checked
// out of the pool.
mw.startNewCycle(0)
if g, w := mw.maxSessionsCheckedOut[0], uint64(0); g != w {
t.Fatalf("Max sessions checked out mismatch.\nGot: %d\nWant: %d", g, w)
}
for _, m := range mw.maxSessionsCheckedOut[1:] {
if m < maxOpened {
t.Fatalf("Max sessions checked out mismatch.\nGot: %v\nWant: %v", m, maxOpened)
}
}
// Check that the max checked out during the entire window is still
// maxOpened.
if g, w := mw.maxSessionsCheckedOutDuringWindow(), maxOpened; g != w {
t.Fatalf("Max sessions checked out during window mismatch.\nGot: %d\nWant: %d", g, w)
}
// Update the max number checked out for the current cycle.
mw.updateMaxSessionsCheckedOutDuringWindow(uint64(10))
if g, w := mw.maxSessionsCheckedOut[0], uint64(10); g != w {
t.Fatalf("Max sessions checked out mismatch.\nGot: %d\nWant: %d", g, w)
}
// The max of the entire window should still not change.
if g, w := mw.maxSessionsCheckedOutDuringWindow(), maxOpened; g != w {
t.Fatalf("Max sessions checked out during window mismatch.\nGot: %d\nWant: %d", g, w)
}
// Now pass enough cycles to complete a maintenance window. Each cycle has
// no sessions checked out. We start at 1, as we have already passed one
// cycle. This should then be the last cycle still in the maintenance
// window, and the only one with a maxSessionsCheckedOut greater than 0.
for i := 1; i < maintenanceWindowSize; i++ {
mw.startNewCycle(0)
}
for _, m := range mw.maxSessionsCheckedOut[:9] {
if m != 0 {
t.Fatalf("Max sessions checked out mismatch.\nGot: %v\nWant: %v", m, 0)
}
}
// The oldest cycle in the window should have max=10.
if g, w := mw.maxSessionsCheckedOut[maintenanceWindowSize-1], uint64(10); g != w {
t.Fatalf("Max sessions checked out mismatch.\nGot: %d\nWant: %d", g, w)
}
// The max of the entire window should now be 10.
if g, w := mw.maxSessionsCheckedOutDuringWindow(), uint64(10); g != w {
t.Fatalf("Max sessions checked out during window mismatch.\nGot: %d\nWant: %d", g, w)
}
// Do another cycle with max=0.
mw.startNewCycle(0)
// The max of the entire window should now be 0.
if g, w := mw.maxSessionsCheckedOutDuringWindow(), uint64(0); g != w {
t.Fatalf("Max sessions checked out during window mismatch.\nGot: %d\nWant: %d", g, w)
}
// Do another cycle with 5 sessions as max. This should now be the new
// window max.
mw.startNewCycle(5)
if g, w := mw.maxSessionsCheckedOutDuringWindow(), uint64(5); g != w {
t.Fatalf("Max sessions checked out during window mismatch.\nGot: %d\nWant: %d", g, w)
}
// Do a couple of cycles so that the only non-zero value is in the middle.
// The max for the entire window should still be 5.
for i := 0; i < maintenanceWindowSize/2; i++ {
mw.startNewCycle(0)
}
if g, w := mw.maxSessionsCheckedOutDuringWindow(), uint64(5); g != w {
t.Fatalf("Max sessions checked out during window mismatch.\nGot: %d\nWant: %d", g, w)
}
}
|