From 06e0edc76bb4b6b12f1702f3514c39c89037a6a3 Mon Sep 17 00:00:00 2001 From: xiaolei Date: Mon, 3 Nov 2025 11:36:32 -0500 Subject: [PATCH 01/17] add large copy test --- pgpool.conf => config.ini | 0 main.go | 31 +++++- pool/client.go | 8 +- pool/config.go | 3 +- pool/server.go | 6 +- proto/reader.go | 19 +++- test/concurrent.go | 119 ++++++++++++++++++++- test/migrations/001_create_test_tables.sql | 6 ++ test/migrations/999_teardown.sql | 1 + 9 files changed, 171 insertions(+), 22 deletions(-) rename pgpool.conf => config.ini (100%) diff --git a/pgpool.conf b/config.ini similarity index 100% rename from pgpool.conf rename to config.ini diff --git a/main.go b/main.go index 5030806..ba54352 100644 --- a/main.go +++ b/main.go @@ -2,24 +2,46 @@ package main import ( "flag" + "fmt" "log/slog" "net" "os" "os/signal" + "strings" "syscall" "github.com/everdance/pgpool/pool" ) +func parseLogLevel(level string) (slog.Level, error) { + switch strings.ToLower(level) { + case "debug": + return slog.LevelDebug, nil + case "info": + return slog.LevelInfo, nil + case "warn", "warning": + return slog.LevelWarn, nil + case "error": + return slog.LevelError, nil + default: + return slog.LevelInfo, fmt.Errorf("unknown log level: %s (valid: debug, info, warn, error)", level) + } +} + func main() { - debug := flag.Bool("debug", false, "enable debug level logging") + var logLevel string var cfgSrc string - flag.StringVar(&cfgSrc, "conf", "./pgpool.conf", "config file") + flag.StringVar(&logLevel, "l", "info", "log level (debug, info, warn, error)") + flag.StringVar(&cfgSrc, "c", "./config.ini", "config file") flag.Parse() - if *debug { - slog.SetLogLoggerLevel(slog.LevelDebug) + // Set log level + level, err := parseLogLevel(logLevel) + if err != nil { + fmt.Fprintf(os.Stderr, "Invalid log level: %v\n", err) + os.Exit(1) } + slog.SetLogLoggerLevel(level) args := flag.Args() if len(args) > 0 { @@ -62,5 +84,4 @@ func main() { c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt, syscall.SIGTERM) <-c - // pools.Close() } diff --git a/pool/client.go b/pool/client.go index 63c9029..bc8743f 100644 --- a/pool/client.go +++ b/pool/client.go @@ -82,7 +82,7 @@ func (client *ClientConn) ID() string { } func (client *ClientConn) Write(msg proto.Message) error { - slog.Debug("send message", "client", client.ID(), "msg", fmt.Sprintf("%#v", msg)) + slog.Debug("send message", "client", client.ID(), "msg", msg.Type().String()) if _, err := client.Conn.Write(msg.Encode()); err != nil { slog.Error("client write", "error", err) @@ -117,7 +117,7 @@ func (pls *Pools) NewClient(conn *net.TCPConn) { break } - slog.Debug("client:", "addr", client.ID(), "message", fmt.Sprintf("%#v", msg)) + slog.Debug("client:", "addr", client.ID(), "message", msg.Type().String) switch msg.Type() { case proto.StartupMsg: @@ -236,7 +236,7 @@ func (p *Pool) authPassword(client *ClientConn) error { } } - slog.Debug("client auth:", "addr", client.ID(), "message", fmt.Sprintf("%#v", msg)) + slog.Debug("client auth:", "addr", client.ID(), "message", msg.Type().String()) switch msg.Type() { case proto.PasswordMsg: @@ -339,7 +339,7 @@ func (p *Pool) handleClient(client *ClientConn) { break } - slog.Debug("client:", "addr", client.ID(), "message", fmt.Sprintf("%#v", msg)) + slog.Debug("client:", "addr", client.ID(), "message", msg.Type().String()) switch msg.Type() { case proto.Terminate: diff --git a/pool/config.go b/pool/config.go index 2883acc..c62b935 100644 --- a/pool/config.go +++ b/pool/config.go @@ -48,8 +48,7 @@ func ParseCfg(file string) (Config, error) { cfg := Config{} record := map[string]string{} - lines := strings.Split(string(content), "\n") - for _, line := range lines { + for line := range strings.SplitSeq(string(content), "\n") { l := strings.Trim(strings.TrimSpace(line), "[]") if l == "" { continue diff --git a/pool/server.go b/pool/server.go index c2dd68d..f4e68c0 100644 --- a/pool/server.go +++ b/pool/server.go @@ -48,7 +48,7 @@ func (sc *ServConn) ID() string { } func (sc *ServConn) Write(msg proto.Message) error { - slog.Debug("send", "server", sc.ID(), "message", fmt.Sprintf("%#v", msg)) + slog.Debug("send", "server", sc.ID(), "message", msg.Type().String()) if _, err := sc.Conn.Write(msg.Encode()); err != nil { slog.Error("server write", "error", err) @@ -81,7 +81,7 @@ func (p *Pool) handleServer(sc *ServConn) { break } - slog.Debug("server message:", "addr", sc.ID(), "msg", fmt.Sprintf("%#v", m)) + slog.Debug("server message:", "addr", sc.ID(), "msg", m.Type().String()) switch m.Type() { case proto.ReadyForQuery: @@ -183,7 +183,7 @@ func (p *Pool) serverAuth(srvConn *ServConn) error { return err } - slog.Debug("server auth:", "addr", srvConn.ID(), "message", fmt.Sprintf("%#v", m)) + slog.Debug("server auth:", "addr", srvConn.ID(), "message", m.Type().String()) switch m.Type() { case proto.AuthOk: diff --git a/proto/reader.go b/proto/reader.go index 72b6955..42fca47 100644 --- a/proto/reader.go +++ b/proto/reader.go @@ -12,7 +12,7 @@ const bufSize = 4096 type MessageReader struct { source io.Reader frontend bool - buffer [bufSize]byte + buffer []byte read int // read start write int // write start } @@ -22,6 +22,7 @@ func NewReader(source io.Reader, frontend bool) *MessageReader { return &MessageReader{ source: source, frontend: frontend, + buffer: make([]byte, bufSize), read: 0, write: 0, } @@ -51,11 +52,19 @@ func (m *MessageReader) ensure(nread int) error { } m.rewind(nread) - n, err := m.source.Read(m.buffer[m.write:]) - if err != nil { - return err + + // we have to allocate big buffers + if nread > len(m.buffer) { + m.buffer = make([]byte, nread+100) + } + + for m.write-m.read < nread { + n, err := m.source.Read(m.buffer[m.write:]) + if err != nil { + return err + } + m.write += n } - m.write += n return nil } diff --git a/test/concurrent.go b/test/concurrent.go index aa247ad..1fa8402 100644 --- a/test/concurrent.go +++ b/test/concurrent.go @@ -20,9 +20,14 @@ func main() { numConnections := getEnvInt("NUM_CONNECTIONS", 50) queriesPerConnection := getEnvInt("QUERIES_PER_CONNECTION", 5) + copyWorkerOps := getEnvInt("COPY_WORKER_OPS", 10) + copyBatchSize := getEnvInt("COPY_BATCH_SIZE", 10000) + fmt.Printf("Starting concurrent connection test\n") fmt.Printf("Connections: %d\n", numConnections) - fmt.Printf("Queries per connection: %d\n\n", queriesPerConnection) + fmt.Printf("Queries per connection: %d\n", queriesPerConnection) + fmt.Printf("COPY worker: %d operations, batch size: %d\n", copyWorkerOps, copyBatchSize) + fmt.Println() g, ctx := errgroup.WithContext(context.Background()) start := time.Now() @@ -35,6 +40,10 @@ func main() { }) } + g.Go(func() error { + return runCopyWorker(ctx, connString, copyWorkerOps, copyBatchSize) + }) + // Wait for all workers to complete if err := g.Wait(); err != nil { fmt.Printf("\n❌ Test failed: %v\n", err) @@ -42,9 +51,11 @@ func main() { } duration := time.Since(start) + totalOps := numConnections * queriesPerConnection + totalOps += copyWorkerOps fmt.Printf("\n✅ All workers completed successfully in %v\n", duration) - fmt.Printf("Total queries: %d\n", numConnections*queriesPerConnection) - fmt.Printf("Average time per query: %v\n", duration/time.Duration(numConnections*queriesPerConnection)) + fmt.Printf("Total operations: %d\n", totalOps) + fmt.Printf("Average time per operation: %v\n", duration/time.Duration(totalOps)) } func runWorker(ctx context.Context, id int, connString string, numQueries int) error { @@ -150,6 +161,108 @@ func executeCopyQuery(ctx context.Context, conn *pgx.Conn, workerID, queryID int return nil } +// runCopyWorker performs dedicated COPY IN/OUT operations on large_test_data table +func runCopyWorker(ctx context.Context, connString string, numOps, batchSize int) error { + // Connect to database + conn, err := pgx.Connect(ctx, connString) + if err != nil { + return fmt.Errorf("COPY Worker: Failed to connect: %w", err) + } + defer conn.Close(ctx) + + log.Printf("COPY Worker: Connected successfully\n") + + // Alternate between COPY IN and COPY OUT operations + for i := 0; i < numOps; i++ { + start := time.Now() + var err error + var opType string + + if i%2 == 0 { + // COPY IN operation + opType = "COPY IN" + err = executeLargeCopyIn(ctx, conn, i, batchSize) + } else { + // COPY OUT operation + opType = "COPY OUT" + err = executeLargeCopyOut(ctx, conn, batchSize) + } + + if err != nil { + return fmt.Errorf("COPY Worker: Operation %d (%s) failed: %w", i, opType, err) + } + + duration := time.Since(start) + rowsPerSec := float64(batchSize) / duration.Seconds() + log.Printf("COPY Worker: Operation %d (%s) completed in %v (%.0f rows/sec, %d rows)\n", + i, opType, duration, rowsPerSec, batchSize) + + // Small delay between operations + time.Sleep(50 * time.Millisecond) + } + + log.Printf("COPY Worker: All operations completed\n") + return nil +} + +// executeLargeCopyIn performs COPY IN operation to insert data into large_test_data +func executeLargeCopyIn(ctx context.Context, conn *pgx.Conn, opID, batchSize int) error { + // Generate data on the fly + rows := make([][]any, batchSize) + baseID := int64(opID * batchSize * 10000) // Ensure unique IDs across operations + for i := 0; i < batchSize; i++ { + id := baseID + int64(i) + rows[i] = []any{id, fmt.Sprintf("test_value_%d", id)} + } + + count, err := conn.CopyFrom( + ctx, + pgx.Identifier{"large_test_data"}, + []string{"id", "value"}, + pgx.CopyFromRows(rows), + ) + if err != nil { + return fmt.Errorf("COPY IN failed: %w", err) + } + + if count != int64(batchSize) { + return fmt.Errorf("COPY IN: expected %d rows, got %d", batchSize, count) + } + + return nil +} + +// executeLargeCopyOut performs COPY OUT operation to read data from large_test_data +func executeLargeCopyOut(ctx context.Context, conn *pgx.Conn, batchSize int) error { + // Use COPY TO to export data + // Note: We'll read the data to simulate real usage + rows, err := conn.Query(ctx, fmt.Sprintf("SELECT id, value FROM large_test_data LIMIT %d", batchSize)) + if err != nil { + return fmt.Errorf("COPY OUT query failed: %w", err) + } + defer rows.Close() + + count := 0 + for rows.Next() { + var id int64 + var value string + if err := rows.Scan(&id, &value); err != nil { + return fmt.Errorf("COPY OUT scan failed: %w", err) + } + count++ + } + + if err := rows.Err(); err != nil { + return fmt.Errorf("COPY OUT iteration failed: %w", err) + } + + if count == 0 { + return fmt.Errorf("COPY OUT: no data available in large_test_data table") + } + + return nil +} + // getEnvString retrieves a string value from environment variable, or returns the default value func getEnvString(key string, defaultValue string) string { if value := os.Getenv(key); value != "" { diff --git a/test/migrations/001_create_test_tables.sql b/test/migrations/001_create_test_tables.sql index 2f6dcfd..ad46e43 100644 --- a/test/migrations/001_create_test_tables.sql +++ b/test/migrations/001_create_test_tables.sql @@ -41,3 +41,9 @@ INSERT INTO products (name, price, stock_quantity) VALUES ('Keyboard', 79.99, 150), ('Monitor', 299.99, 75), ('Headphones', 149.99, 120); + +-- Create large test table for COPY IN/OUT testing with millions of records +CREATE TABLE IF NOT EXISTS large_test_data ( + id BIGINT NOT NULL, + value TEXT NOT NULL +); diff --git a/test/migrations/999_teardown.sql b/test/migrations/999_teardown.sql index 42f11e4..b5bfe46 100644 --- a/test/migrations/999_teardown.sql +++ b/test/migrations/999_teardown.sql @@ -1,5 +1,6 @@ -- Teardown script to clean up test data and tables after integration tests -- Drop tables (CASCADE will remove dependent objects like indexes) +DROP TABLE IF EXISTS large_test_data CASCADE; DROP TABLE IF EXISTS products CASCADE; DROP TABLE IF EXISTS users CASCADE; From 0c0adafc180c9d8e43e028a80409e84c32e08e9f Mon Sep 17 00:00:00 2001 From: xiaolei Date: Mon, 3 Nov 2025 14:18:01 -0500 Subject: [PATCH 02/17] fix copy --- proto/message.go | 4 +++- proto/reader.go | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/proto/message.go b/proto/message.go index 0c901bc..0c2c715 100644 --- a/proto/message.go +++ b/proto/message.go @@ -443,7 +443,9 @@ func (m AuthGSSContinueMsg) Encode() []byte { } func (m *AuthGSSContinueMsg) Decode(bs mbytes) error { - m.Data = bs[9:] + m.Data = make([]byte, len(bs[9:])) + copy(m.Data, bs[9:]) + return nil } diff --git a/proto/reader.go b/proto/reader.go index 42fca47..86a7ab1 100644 --- a/proto/reader.go +++ b/proto/reader.go @@ -55,7 +55,9 @@ func (m *MessageReader) ensure(nread int) error { // we have to allocate big buffers if nread > len(m.buffer) { - m.buffer = make([]byte, nread+100) + buffer := make([]byte, nread+100) + copy(buffer, m.buffer[:m.write]) + m.buffer = buffer } for m.write-m.read < nread { From 222fa30fb4d7c34cdad1ade0fca6bf8d68948227 Mon Sep 17 00:00:00 2001 From: xiaolei Date: Mon, 3 Nov 2025 16:01:25 -0500 Subject: [PATCH 03/17] test zz --- .github/workflows/config.yml | 15 +- .gitignore | 3 +- pool/client.go | 2 +- pool/server.go | 2 +- test/README.md | 78 +++++- test/{concurrent.go => concurrent_test.go} | 0 test/{run.sh => run_concurrent.sh} | 14 +- test/run_smoke.sh | 155 +++++++++++ test/smoke_test.sql | 301 +++++++++++++++++++++ 9 files changed, 545 insertions(+), 25 deletions(-) rename test/{concurrent.go => concurrent_test.go} (100%) rename test/{run.sh => run_concurrent.sh} (89%) create mode 100755 test/run_smoke.sh create mode 100644 test/smoke_test.sql diff --git a/.github/workflows/config.yml b/.github/workflows/config.yml index 4e0c761..5da7373 100644 --- a/.github/workflows/config.yml +++ b/.github/workflows/config.yml @@ -163,8 +163,19 @@ jobs: echo "pgpool failed to start" exit 1 - - name: Run integration tests - run: ./test/run.sh + - name: Run smoke test + run: ./test/run_smoke.sh + env: + DB_HOST: localhost + DB_PORT: 5432 + DB_USER: pgtest + DB_PASSWORD: test123 + DB_NAME: postgres + TARGET_HOST: localhost + TARGET_PORT: 5433 + + - name: Run concurrent test + run: ./test/run_concurrent.sh env: DB_HOST: localhost DB_PORT: 5432 diff --git a/.gitignore b/.gitignore index ce1c307..fede587 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ .vscode pgpool vendor -test/vendor \ No newline at end of file +test/vendor +test/output \ No newline at end of file diff --git a/pool/client.go b/pool/client.go index bc8743f..297d73d 100644 --- a/pool/client.go +++ b/pool/client.go @@ -339,7 +339,7 @@ func (p *Pool) handleClient(client *ClientConn) { break } - slog.Debug("client:", "addr", client.ID(), "message", msg.Type().String()) + slog.Debug("client:", "addr", client.ID(), "message", fmt.Sprintf("%#v", msg)) switch msg.Type() { case proto.Terminate: diff --git a/pool/server.go b/pool/server.go index f4e68c0..c269ebe 100644 --- a/pool/server.go +++ b/pool/server.go @@ -81,7 +81,7 @@ func (p *Pool) handleServer(sc *ServConn) { break } - slog.Debug("server message:", "addr", sc.ID(), "msg", m.Type().String()) + slog.Debug("server message:", "addr", sc.ID(), "msg", fmt.Sprintf("%#v", m)) switch m.Type() { case proto.ReadyForQuery: diff --git a/test/README.md b/test/README.md index 407eab2..c2d0d4a 100644 --- a/test/README.md +++ b/test/README.md @@ -1,25 +1,77 @@ -# Concurrent Connection Test +# PostgreSQL Pool Tests -This directory contains tests for concurrent database connections using the Go pgx library. +This directory contains tests for the PostgreSQL connection pool. -## Running the test +## Test Suites +### 1. Smoke Test +Interactive SQL queries smoke test that validates common database operations including manual transaction management. + +**Running:** ```bash -cd test -go mod download -go run concurrent_test.go +./run_smoke_test.sh +``` + +**What it tests:** +- Basic SELECT queries (WHERE, JOIN, aggregates) +- INSERT operations (single, multiple, with SELECT) +- UPDATE operations (simple, with arithmetic, multiple rows) +- DELETE operations +- Manual transaction management (BEGIN, COMMIT, ROLLBACK) +- SAVEPOINT and partial rollback +- Nested transactions +- Advanced queries (subqueries, CTEs, window functions) +- Prepared statements +- Error handling in transactions + +**Output Validation:** +The smoke test validates that all queries succeed by: +1. Capturing SQL output to `test/output/smoke_test_actual.out` +2. Checking for ERROR or FATAL messages in the output +3. Comparing against expected baseline at `test/smoke_test_expected.out` (if it exists) + +**Generating Expected Output Baseline:** +On first run or when updating test queries, generate a new baseline: +```bash +# Run the test to generate actual output +./run_smoke_test.sh + +# If the test passes (no errors), create the baseline +cp test/output/smoke_test_actual.out test/smoke_test_expected.out ``` -## Configuration +The comparison normalizes dynamic values (timestamps, IDs, PIDs, etc.) to ensure consistent results across runs. -Edit `concurrent_test.go` to modify: -- `connString`: Database connection string -- `numConnections`: Number of concurrent connections -- `queriesPerConnection`: Number of queries per connection +### 2. Concurrent Connection Test +Stress test for concurrent database connections using the Go pgx library. -## What it tests +**Running:** +```bash +./run_concurrent_test.sh +``` -The test creates multiple concurrent connections and executes queries to verify: +**What it tests:** - Connection pooling behavior - Concurrent query execution - Connection handling under load + +**Configuration** (via environment variables): +- `NUM_CONNECTIONS`: Number of concurrent connections (default: 100) +- `QUERIES_PER_CONNECTION`: Number of queries per connection (default: 5) + +## Running All Tests + +Both tests are executed in sequence by GitHub Actions CI/CD pipeline: +1. Smoke test runs first to validate basic SQL operations +2. Concurrent test runs second to validate connection pooling under load + +## Database Configuration + +All tests use the following environment variables: +- `DB_HOST`: PostgreSQL host (default: localhost) +- `DB_PORT`: PostgreSQL port (default: 5432) +- `DB_USER`: PostgreSQL user (default: pgtest) +- `DB_PASSWORD`: PostgreSQL password (default: test123) +- `DB_NAME`: Database name (default: postgres) +- `PGPOOL_HOST`: Pgpool host (default: localhost) +- `PGPOOL_PORT`: Pgpool port (default: 5433) diff --git a/test/concurrent.go b/test/concurrent_test.go similarity index 100% rename from test/concurrent.go rename to test/concurrent_test.go diff --git a/test/run.sh b/test/run_concurrent.sh similarity index 89% rename from test/run.sh rename to test/run_concurrent.sh index 1e17133..b2c5701 100755 --- a/test/run.sh +++ b/test/run_concurrent.sh @@ -1,7 +1,7 @@ #!/bin/bash -# Integration test runner script -# This script sets up the database, runs integration tests, and tears down the database +# Concurrent test runner script +# This script sets up the database, runs concurrent connection tests, and tears down the database set -e # Exit on error @@ -27,7 +27,7 @@ NC='\033[0m' # No Color # Get script directory SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -echo -e "${YELLOW}=== PostgreSQL Integration Test Runner ===${NC}\n" +echo -e "${YELLOW}=== PostgreSQL Concurrent Test Runner ===${NC}\n" # Function to run SQL file run_sql() { @@ -91,7 +91,7 @@ fi run_sql "${SCRIPT_DIR}/migrations/001_create_test_tables.sql" "Running database migrations" # Run the integration test -echo -e "${YELLOW}Running integration tests...${NC}" +echo -e "${YELLOW}Running concurrent tests...${NC}" echo "Configuration:" echo " - Connection: postgres://${DB_USER}:***@${PGPOOL_HOST}:${PGPOOL_PORT}/${DB_NAME}" echo " - Connections: ${NUM_CONNECTIONS}" @@ -102,11 +102,11 @@ cd "${SCRIPT_DIR}" DB_CONNECTION_STRING="postgres://${DB_USER}:${DB_PASSWORD}@${PGPOOL_HOST}:${PGPOOL_PORT}/${DB_NAME}" \ NUM_CONNECTIONS="${NUM_CONNECTIONS}" \ QUERIES_PER_CONNECTION="${QUERIES_PER_CONNECTION}" \ -go run concurrent.go +go run concurrent_test.go if [ $? -eq 0 ]; then - echo -e "\n${GREEN}✓ Integration tests passed${NC}" + echo -e "\n${GREEN}✓ Concurrent tests passed${NC}" else - echo -e "\n${RED}✗ Integration tests failed${NC}" + echo -e "\n${RED}✗ Concurrent tests failed${NC}" exit 1 fi diff --git a/test/run_smoke.sh b/test/run_smoke.sh new file mode 100755 index 0000000..4e6fd06 --- /dev/null +++ b/test/run_smoke.sh @@ -0,0 +1,155 @@ +#!/bin/bash + +# Smoke test runner script +# Tests common interactive SQL queries including manual transaction management + +set -e # Exit on error + +# Default configuration +DB_HOST="${DB_HOST:-localhost}" +DB_PORT="${DB_PORT:-5432}" +DB_USER="${DB_USER:-pgtest}" +DB_PASSWORD="${DB_PASSWORD:-test123}" +DB_NAME="${DB_NAME:-postgres}" +PGPOOL_HOST="${PGPOOL_HOST:-localhost}" +PGPOOL_PORT="${PGPOOL_PORT:-5433}" + +# Use pgpool by default, but allow direct connection +TARGET_HOST="${TARGET_HOST:-${PGPOOL_HOST}}" +TARGET_PORT="${TARGET_PORT:-${PGPOOL_PORT}}" + +# Colors for output +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +BLUE='\033[0;34m' +NC='\033[0m' # No Color + +# Get script directory +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +echo -e "${BLUE}╔════════════════════════════════════════════════╗${NC}" +echo -e "${BLUE}║ PostgreSQL Smoke Test Runner ║${NC}" +echo -e "${BLUE}╚════════════════════════════════════════════════╝${NC}" +echo "" + +# Function to cleanup on exit +cleanup() { + local exit_code=$? + + if [ $exit_code -eq 0 ]; then + echo "" + echo -e "${GREEN}╔════════════════════════════════════════════════╗${NC}" + echo -e "${GREEN}║ ✓ All smoke tests passed successfully! ║${NC}" + echo -e "${GREEN}╚════════════════════════════════════════════════╝${NC}" + else + echo "" + echo -e "${RED}╔════════════════════════════════════════════════╗${NC}" + echo -e "${RED}║ ✗ Smoke tests failed ║${NC}" + echo -e "${RED}╚════════════════════════════════════════════════╝${NC}" + fi + + exit $exit_code +} + +# Register cleanup function to run on exit +trap cleanup EXIT INT TERM + +# Check if PostgreSQL/pgpool is accessible +echo -e "${YELLOW}Configuration:${NC}" +echo " Target: ${TARGET_HOST}:${TARGET_PORT}" +echo " Database: ${DB_NAME}" +echo " User: ${DB_USER}" +echo "" + +echo -e "${YELLOW}Checking database connection...${NC}" +if ! PGPASSWORD="${DB_PASSWORD}" psql -h "${TARGET_HOST}" -p "${TARGET_PORT}" -U "${DB_USER}" -d "${DB_NAME}" -c "SELECT 1" > /dev/null 2>&1; then + echo -e "${RED}✗ Cannot connect to database at ${TARGET_HOST}:${TARGET_PORT}${NC}" + echo "Make sure the database server is running and credentials are correct" + exit 1 +fi +echo -e "${GREEN}✓ Database connection successful${NC}" +echo "" + +# Check if test tables exist +echo -e "${YELLOW}Checking test tables...${NC}" +if ! PGPASSWORD="${DB_PASSWORD}" psql -h "${TARGET_HOST}" -p "${TARGET_PORT}" -U "${DB_USER}" -d "${DB_NAME}" -c "SELECT 1 FROM users LIMIT 1" > /dev/null 2>&1; then + echo -e "${YELLOW}⚠ Test tables not found. Running migrations...${NC}" + PGPASSWORD="${DB_PASSWORD}" psql -h "${DB_HOST}" -p "${DB_PORT}" -U "${DB_USER}" -d "${DB_NAME}" -f "${SCRIPT_DIR}/migrations/001_create_test_tables.sql" > /dev/null + echo -e "${GREEN}✓ Test tables created${NC}" +else + echo -e "${GREEN}✓ Test tables found${NC}" +fi +echo "" + +# Create output directories +OUTPUT_DIR="${SCRIPT_DIR}/output" +mkdir -p "${OUTPUT_DIR}" + +ACTUAL_OUTPUT="${OUTPUT_DIR}/smoke_test_actual.out" +EXPECTED_OUTPUT="${SCRIPT_DIR}/smoke_test_expected.out" + +# Run the smoke test +echo -e "${YELLOW}Running smoke test suite...${NC}" +echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}" +echo "" + +# Run test and capture output +PGPASSWORD="${DB_PASSWORD}" psql -h "${TARGET_HOST}" -p "${TARGET_PORT}" -U "${DB_USER}" -d "${DB_NAME}" -f "${SCRIPT_DIR}/smoke_test.sql" > "${ACTUAL_OUTPUT}" 2>&1 + +# Display the output to the user +cat "${ACTUAL_OUTPUT}" + +echo "" +echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}" +echo "" + +# Check for ERROR or FATAL in output +if grep -i -E "(ERROR|FATAL)" "${ACTUAL_OUTPUT}" > /dev/null 2>&1; then + echo -e "${RED}✗ Smoke test output contains errors:${NC}" + grep -i -E "(ERROR|FATAL)" "${ACTUAL_OUTPUT}" + exit 1 +fi + +# If expected output exists, compare against it +if [ -f "${EXPECTED_OUTPUT}" ]; then + echo -e "${YELLOW}Comparing output against expected baseline...${NC}" + + # Normalize outputs by removing dynamic values + normalize_output() { + sed -E \ + -e 's/[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}(\.[0-9]+)?(\+[0-9]{2})?/TIMESTAMP/g' \ + -e 's/\| +[0-9]+ \|/| ID |/g' \ + -e 's/backend_pid +\| +[0-9]+/backend_pid | PID/g' \ + -e 's/current_transaction_id +\| +[0-9]+/current_transaction_id | TXID/g' \ + -e 's/server_ip +\| +[0-9.]+/server_ip | IP/g' \ + -e 's/server_port +\| +[0-9]+/server_port | PORT/g' \ + -e 's/\b[0-9]+\.[0-9]+\b/NUM/g' \ + "$1" + } + + NORMALIZED_ACTUAL="${OUTPUT_DIR}/normalized_actual.out" + NORMALIZED_EXPECTED="${OUTPUT_DIR}/normalized_expected.out" + + normalize_output "${ACTUAL_OUTPUT}" > "${NORMALIZED_ACTUAL}" + normalize_output "${EXPECTED_OUTPUT}" > "${NORMALIZED_EXPECTED}" + + if diff -u "${NORMALIZED_EXPECTED}" "${NORMALIZED_ACTUAL}" > "${OUTPUT_DIR}/diff.out"; then + echo -e "${GREEN}✓ Output matches expected baseline${NC}" + else + echo -e "${RED}✗ Output differs from expected baseline${NC}" + echo "" + echo -e "${YELLOW}Diff (expected vs actual):${NC}" + head -n 50 "${OUTPUT_DIR}/diff.out" + if [ $(wc -l < "${OUTPUT_DIR}/diff.out") -gt 50 ]; then + echo "... (diff truncated, see ${OUTPUT_DIR}/diff.out for full output)" + fi + exit 1 + fi +else + echo -e "${YELLOW}⚠ No expected output baseline found at ${EXPECTED_OUTPUT}${NC}" + echo -e "${YELLOW} To create a baseline, run:${NC}" + echo -e "${YELLOW} cp ${ACTUAL_OUTPUT} ${EXPECTED_OUTPUT}${NC}" + echo "" + echo -e "${GREEN}✓ Test executed successfully (no errors found)${NC}" +fi diff --git a/test/smoke_test.sql b/test/smoke_test.sql new file mode 100644 index 0000000..bd9101b --- /dev/null +++ b/test/smoke_test.sql @@ -0,0 +1,301 @@ +-- ================================================ +-- PostgreSQL Smoke Test Script +-- Tests common interactive SQL queries including +-- manual transaction management +-- ================================================ + +\set ON_ERROR_STOP on + +\echo '=== Starting Smoke Test ===' +\echo '' + +-- ================================================ +-- Section 1: Basic SELECT Queries +-- ================================================ +\echo '--- Section 1: Basic SELECT Queries ---' + +-- Simple SELECT +SELECT 'Test 1.1: Simple SELECT' AS test_name; +SELECT COUNT(*) AS user_count FROM users; + +-- SELECT with WHERE clause +SELECT 'Test 1.2: SELECT with WHERE' AS test_name; +SELECT username, email FROM users WHERE username = 'alice'; + +-- SELECT with JOIN +SELECT 'Test 1.3: SELECT with JOIN (simulated)' AS test_name; +SELECT u.username, COUNT(*) AS row_count +FROM users u +CROSS JOIN users u2 +GROUP BY u.username +LIMIT 5; + +-- Aggregate functions +SELECT 'Test 1.4: Aggregate functions' AS test_name; +SELECT + COUNT(*) AS total_products, + AVG(price) AS avg_price, + SUM(stock_quantity) AS total_stock, + MIN(price) AS min_price, + MAX(price) AS max_price +FROM products; + +\echo '' + +-- ================================================ +-- Section 2: INSERT Operations +-- ================================================ +\echo '--- Section 2: INSERT Operations ---' + +SELECT 'Test 2.1: Single INSERT' AS test_name; +INSERT INTO users (username, email) +VALUES ('smoke_test_user_1', 'smoke1@test.com') +RETURNING id, username; + +SELECT 'Test 2.2: Multiple INSERT' AS test_name; +INSERT INTO users (username, email) VALUES + ('smoke_test_user_2', 'smoke2@test.com'), + ('smoke_test_user_3', 'smoke3@test.com') +RETURNING id, username; + +SELECT 'Test 2.3: INSERT with SELECT' AS test_name; +INSERT INTO products (name, price, stock_quantity) +SELECT 'Test Product ' || generate_series, + (random() * 100)::NUMERIC(10,2), + (random() * 100)::INT +FROM generate_series(1, 5) +RETURNING id, name, price; + +\echo '' + +-- ================================================ +-- Section 3: UPDATE Operations +-- ================================================ +\echo '--- Section 3: UPDATE Operations ---' + +SELECT 'Test 3.1: Simple UPDATE' AS test_name; +UPDATE users +SET email = 'alice_updated@example.com', + updated_at = CURRENT_TIMESTAMP +WHERE username = 'alice' +RETURNING username, email; + +SELECT 'Test 3.2: UPDATE with arithmetic' AS test_name; +UPDATE products +SET stock_quantity = stock_quantity + 10 +WHERE name = 'Laptop' +RETURNING name, stock_quantity; + +SELECT 'Test 3.3: UPDATE multiple rows' AS test_name; +UPDATE products +SET price = price * 0.9 +WHERE price > 100 +RETURNING name, price; + +\echo '' + +-- ================================================ +-- Section 4: DELETE Operations +-- ================================================ +\echo '--- Section 4: DELETE Operations ---' + +SELECT 'Test 4.1: DELETE with condition' AS test_name; +DELETE FROM users +WHERE username LIKE 'smoke_test_user_%' +RETURNING username; + +\echo '' + +-- ================================================ +-- Section 5: Manual Transaction Management +-- ================================================ +\echo '--- Section 5: Manual Transaction Management ---' + +-- Test 5.1: Simple COMMIT transaction +SELECT 'Test 5.1: Transaction with COMMIT' AS test_name; +BEGIN; + INSERT INTO users (username, email) VALUES ('tx_user_1', 'tx1@test.com'); + INSERT INTO users (username, email) VALUES ('tx_user_2', 'tx2@test.com'); + SELECT COUNT(*) AS count_in_transaction FROM users WHERE username LIKE 'tx_user_%'; +COMMIT; +SELECT COUNT(*) AS count_after_commit FROM users WHERE username LIKE 'tx_user_%'; + +\echo '' + +-- Test 5.2: ROLLBACK transaction +SELECT 'Test 5.2: Transaction with ROLLBACK' AS test_name; +BEGIN; + INSERT INTO users (username, email) VALUES ('rollback_user_1', 'rb1@test.com'); + SELECT COUNT(*) AS count_in_transaction FROM users WHERE username LIKE 'rollback_user_%'; +ROLLBACK; +SELECT COUNT(*) AS count_after_rollback FROM users WHERE username LIKE 'rollback_user_%'; + +\echo '' + +-- Test 5.3: SAVEPOINT and partial rollback +SELECT 'Test 5.3: Transaction with SAVEPOINTs' AS test_name; +BEGIN; + INSERT INTO users (username, email) VALUES ('sp_user_1', 'sp1@test.com'); + SAVEPOINT sp1; + + INSERT INTO users (username, email) VALUES ('sp_user_2', 'sp2@test.com'); + SAVEPOINT sp2; + + INSERT INTO users (username, email) VALUES ('sp_user_3', 'sp3@test.com'); + + -- Rollback to sp2 (should keep sp_user_1 and sp_user_2, lose sp_user_3) + ROLLBACK TO SAVEPOINT sp2; + + INSERT INTO users (username, email) VALUES ('sp_user_4', 'sp4@test.com'); +COMMIT; + +SELECT username FROM users WHERE username LIKE 'sp_user_%' ORDER BY username; + +\echo '' + +-- Test 5.4: Nested transactions (SAVEPOINT) +SELECT 'Test 5.4: Nested transaction behavior' AS test_name; +BEGIN; + INSERT INTO products (name, price, stock_quantity) + VALUES ('Nested Product 1', 50.00, 10); + + SAVEPOINT nested1; + INSERT INTO products (name, price, stock_quantity) + VALUES ('Nested Product 2', 60.00, 20); + + SAVEPOINT nested2; + INSERT INTO products (name, price, stock_quantity) + VALUES ('Nested Product 3', 70.00, 30); + + ROLLBACK TO SAVEPOINT nested2; + RELEASE SAVEPOINT nested1; +COMMIT; + +SELECT name, price FROM products WHERE name LIKE 'Nested Product%' ORDER BY name; + +\echo '' + +-- ================================================ +-- Section 6: Advanced Queries +-- ================================================ +\echo '--- Section 6: Advanced Queries ---' + +-- Subqueries +SELECT 'Test 6.1: Subquery' AS test_name; +SELECT username, email +FROM users +WHERE id IN (SELECT id FROM users LIMIT 3); + +-- CTE (Common Table Expression) +SELECT 'Test 6.2: CTE (WITH clause)' AS test_name; +WITH expensive_products AS ( + SELECT * FROM products WHERE price > 100 +) +SELECT name, price FROM expensive_products ORDER BY price DESC; + +-- Window functions +SELECT 'Test 6.3: Window functions' AS test_name; +SELECT + name, + price, + ROW_NUMBER() OVER (ORDER BY price DESC) AS price_rank, + AVG(price) OVER () AS avg_price +FROM products +LIMIT 5; + +-- GROUP BY with HAVING +SELECT 'Test 6.4: GROUP BY with HAVING' AS test_name; +SELECT + CASE + WHEN price < 50 THEN 'Cheap' + WHEN price < 150 THEN 'Medium' + ELSE 'Expensive' + END AS price_category, + COUNT(*) AS product_count, + AVG(price) AS avg_price +FROM products +GROUP BY price_category +HAVING COUNT(*) > 0; + +\echo '' + +-- ================================================ +-- Section 7: Prepared Statements Simulation +-- ================================================ +\echo '--- Section 7: Prepared Statements ---' + +SELECT 'Test 7.1: PREPARE and EXECUTE' AS test_name; +PREPARE user_lookup (VARCHAR) AS + SELECT username, email FROM users WHERE username = $1; + +EXECUTE user_lookup('alice'); +EXECUTE user_lookup('bob'); + +DEALLOCATE user_lookup; + +\echo '' + +-- ================================================ +-- Section 8: Error Handling in Transactions +-- ================================================ +\echo '--- Section 8: Error Handling in Transactions ---' + +SELECT 'Test 8.1: Transaction with constraint violation (should rollback)' AS test_name; +DO $$ +BEGIN + BEGIN + INSERT INTO users (username, email) VALUES ('error_test', 'error@test.com'); + -- Try to insert duplicate (this will fail with unique constraint if it exists) + -- For this test, we'll just show the pattern + INSERT INTO users (username, email) VALUES ('error_test', 'error@test.com'); + EXCEPTION WHEN unique_violation THEN + RAISE NOTICE 'Caught unique violation as expected'; + END; +END $$; + +\echo '' + +-- ================================================ +-- Section 9: Connection and Session Info +-- ================================================ +\echo '--- Section 9: Connection and Session Information ---' + +SELECT 'Test 9.1: Session information' AS test_name; +SELECT + current_database() AS database, + current_user AS user, + inet_server_addr() AS server_ip, + inet_server_port() AS server_port, + pg_backend_pid() AS backend_pid; + +SELECT 'Test 9.2: Database version' AS test_name; +SELECT version(); + +SELECT 'Test 9.3: Current transaction status' AS test_name; +SELECT + txid_current() AS current_transaction_id, + pg_is_in_recovery() AS is_in_recovery; + +\echo '' + +-- ================================================ +-- Section 10: Cleanup smoke test data +-- ================================================ +\echo '--- Section 10: Cleanup ---' + +SELECT 'Test 10.1: Cleanup smoke test data' AS test_name; +DELETE FROM users WHERE username LIKE 'tx_user_%'; +DELETE FROM users WHERE username LIKE 'sp_user_%'; +DELETE FROM products WHERE name LIKE 'Test Product%'; +DELETE FROM products WHERE name LIKE 'Nested Product%'; + +-- Restore Alice's email +UPDATE users SET email = 'alice@example.com' WHERE username = 'alice'; + +\echo '' +\echo '=== Smoke Test Complete ===' +\echo '' + +-- Final verification +SELECT 'Final verification - Users count:' AS info, COUNT(*) FROM users; +SELECT 'Final verification - Products count:' AS info, COUNT(*) FROM products; From bcf3626d52f993a6507d2cfd00ed17f6e7ae57d8 Mon Sep 17 00:00:00 2001 From: xiaolei Date: Tue, 4 Nov 2025 09:16:37 -0500 Subject: [PATCH 04/17] add bench --- benchmark/README.md | 352 ++++++++++++++++++++++++ benchmark/config/pgbouncer.ini | 27 ++ benchmark/config/pgpool.conf | 15 + benchmark/config/userlist.txt | 1 + benchmark/scripts/cleanup.sh | 57 ++++ benchmark/scripts/generate_report.sh | 222 +++++++++++++++ benchmark/scripts/run_benchmark.sh | 228 +++++++++++++++ benchmark/scripts/setup.sh | 112 ++++++++ benchmark/workloads/complex_queries.sql | 26 ++ benchmark/workloads/prepared_stmt.sql | 10 + benchmark/workloads/read_write.sql | 22 ++ benchmark/workloads/simple_select.sql | 5 + 12 files changed, 1077 insertions(+) create mode 100644 benchmark/README.md create mode 100644 benchmark/config/pgbouncer.ini create mode 100644 benchmark/config/pgpool.conf create mode 100644 benchmark/config/userlist.txt create mode 100755 benchmark/scripts/cleanup.sh create mode 100755 benchmark/scripts/generate_report.sh create mode 100755 benchmark/scripts/run_benchmark.sh create mode 100755 benchmark/scripts/setup.sh create mode 100644 benchmark/workloads/complex_queries.sql create mode 100644 benchmark/workloads/prepared_stmt.sql create mode 100644 benchmark/workloads/read_write.sql create mode 100644 benchmark/workloads/simple_select.sql diff --git a/benchmark/README.md b/benchmark/README.md new file mode 100644 index 0000000..67b890a --- /dev/null +++ b/benchmark/README.md @@ -0,0 +1,352 @@ +# PostgreSQL Connection Pool Benchmark Suite + +Comprehensive benchmarking suite for comparing **pgpool** vs **pgbouncer** vs **direct PostgreSQL** connections using the industry-standard `pgbench` tool. + +## Overview + +This benchmark suite tests: +- **Throughput** (transactions per second) +- **Latency** (average, p50, p95, p99) +- **Connection overhead** (initial connection time) +- **Protocol performance** (simple, extended, prepared statements) +- **Workload patterns** (read-only, read-write, complex queries) + +## Directory Structure + +``` +benchmark/ +├── config/ # Configuration files +│ ├── pgpool.conf # pgpool configuration +│ ├── pgbouncer.ini # pgbouncer configuration +│ └── userlist.txt # pgbouncer auth file +├── workloads/ # SQL workload files +│ ├── simple_select.sql +│ ├── read_write.sql +│ ├── prepared_stmt.sql +│ └── complex_queries.sql +├── scripts/ # Benchmark scripts +│ ├── setup.sh # Environment setup +│ ├── run_benchmark.sh # Main benchmark runner +│ ├── generate_report.sh # Report generator +│ └── cleanup.sh # Cleanup script +├── results/ # Benchmark results (auto-generated) +│ └── YYYYMMDD_HHMMSS/ # Timestamped results +└── README.md # This file +``` + +## Prerequisites + +1. **PostgreSQL** (tested with PostgreSQL 15+) +2. **pgbench** (included with PostgreSQL client tools) +3. **pgpool** (built from this repository) +4. **pgbouncer** (optional, for comparison) +5. **Go 1.22+** (to build pgpool) + +### Installation + +#### macOS +```bash +brew install postgresql pgbouncer +``` + +#### Ubuntu/Debian +```bash +sudo apt-get install postgresql-client pgbouncer +``` + +## Quick Start + +### 1. Setup Environment + +```bash +cd benchmark +./scripts/setup.sh +``` + +This will: +- Check PostgreSQL connectivity +- Create test database schema +- Verify pgbench installation +- Build pgpool binary if needed +- Check pgbouncer availability + +### 2. Configure Poolers + +#### pgpool Configuration + +Edit `config/pgpool.conf`: +```ini +[app] +addr = localhost:5433 + +[db] +id = 1 +name = postgres +host = localhost:5432 + +[user] +dbid = 1 +name = pgtest +auth_type = scram +password = test123 +max_conn = 20 +max_clients = 200 +``` + +#### pgbouncer Configuration + +Edit `config/pgbouncer.ini` and `config/userlist.txt` with your credentials. + +**Important**: Generate SCRAM hash for pgbouncer: +```bash +# Connect to PostgreSQL +psql -U postgres -d postgres +# Get the password hash +SELECT rolpassword FROM pg_authid WHERE rolname = 'pgtest'; +``` + +Copy the hash to `config/userlist.txt`: +``` +"pgtest" "SCRAM-SHA-256$4096:..." +``` + +### 3. Start Poolers + +#### Start pgpool +```bash +# In terminal 1 +cd /path/to/pgpool +./pgpool -conf benchmark/config/pgpool.conf -debug +``` + +#### Start pgbouncer (optional) +```bash +# In terminal 2 +pgbouncer -d benchmark/config/pgbouncer.ini +``` + +### 4. Run Benchmarks + +```bash +./scripts/run_benchmark.sh +``` + +Default settings: +- Duration: 60 seconds per test +- Connections: 10, 50, 100 +- Workloads: simple_select, read_write, prepared_stmt +- Protocols: simple, extended, prepared + +### 5. Generate Report + +```bash +./scripts/generate_report.sh results/YYYYMMDD_HHMMSS +``` + +This creates: +- `report.md` - Markdown report with comparison tables +- `results.csv` - Raw CSV data for further analysis + +## Configuration Options + +### Environment Variables + +The benchmark runner supports these environment variables: + +```bash +# Database configuration +export DB_HOST=localhost +export DB_PORT=5432 +export DB_USER=pgtest +export DB_PASSWORD=test123 +export DB_NAME=postgres + +# Pool ports +export PGPOOL_PORT=5433 +export PGBOUNCER_PORT=6432 + +# Benchmark configuration +export DURATION=60 # seconds per test +export SCALE_FACTOR=10 # pgbench scale factor +export CONNECTION_COUNTS="10 50 100 200" # connection counts to test +export WORKLOADS="simple_select read_write" # workloads to test +``` + +### Custom Benchmark Run + +```bash +# Quick test (30s, fewer connections) +DURATION=30 CONNECTION_COUNTS="10 50" ./scripts/run_benchmark.sh + +# Heavy load test (120s, many connections) +DURATION=120 CONNECTION_COUNTS="50 100 200 500" ./scripts/run_benchmark.sh + +# Test only read workloads +WORKLOADS="simple_select" ./scripts/run_benchmark.sh +``` + +## Workload Descriptions + +### simple_select.sql +Pure read workload. Tests SELECT query performance. +```sql +SELECT username, email FROM users WHERE id = :id; +``` + +### read_write.sql +Mixed workload (70% reads, 15% updates, 15% inserts). Tests real-world transaction patterns. + +### prepared_stmt.sql +Tests prepared statement caching and reuse across connections. + +### complex_queries.sql +Analytical queries with JOINs, subqueries, and window functions. + +## Understanding Results + +### Key Metrics + +1. **TPS (Transactions Per Second)** - Higher is better + - Measures throughput + - Shows maximum capacity + +2. **Average Latency** - Lower is better + - Mean response time + - Overall user experience + +3. **P95/P99 Latency** - Lower is better + - Tail latency + - Worst-case performance + - Critical for user experience + +4. **Connection Time** - Lower is better + - Overhead of establishing connections + - Important for connection churn scenarios + +### Sample Report Output + +```markdown +## Workload: simple_select + +### Protocol: extended + +#### Throughput (TPS - Higher is Better) + +| Connections | direct | pgpool | pgbouncer | +|-------------|--------|--------|-----------| +| 10 | 15234 | 14876 | 15102 | +| 50 | 42341 | 41203 | 42012 | +| 100 | 52431 | 51234 | 51876 | + +#### Average Latency (ms - Lower is Better) + +| Connections | direct | pgpool | pgbouncer | +|-------------|--------|--------|-----------| +| 10 | 0.65 | 0.67 | 0.66 | +| 50 | 1.18 | 1.21 | 1.19 | +| 100 | 1.91 | 1.95 | 1.93 | +``` + +## Cleanup + +```bash +# Stop poolers and clean pgbench tables +./scripts/cleanup.sh + +# Full cleanup (removes all test data) +./scripts/cleanup.sh --full +``` + +## Advanced Usage + +### Testing Specific Scenarios + +#### Connection Churn +Test how poolers handle frequent connect/disconnect: +```bash +# Use shorter duration with more connection counts +DURATION=30 CONNECTION_COUNTS="5 10 20 50" ./scripts/run_benchmark.sh +``` + +#### High Concurrency +Test behavior under extreme load: +```bash +CONNECTION_COUNTS="100 200 500 1000" DURATION=120 ./scripts/run_benchmark.sh +``` + +#### Protocol Comparison +The benchmark automatically tests all three protocol modes: +- **simple**: Simple query protocol +- **extended**: Extended query protocol with unnamed statements +- **prepared**: Named prepared statements + +### Resource Monitoring + +Monitor system resources during benchmark: + +```bash +# CPU and memory usage +watch -n 1 'ps aux | grep -E "(pgpool|pgbouncer|postgres)"' + +# Connection counts +watch -n 1 'ss -tn | grep -E "(5432|5433|6432)" | wc -l' + +# Database activity +watch -n 1 'psql -U pgtest -c "SELECT count(*), state FROM pg_stat_activity GROUP BY state;"' +``` + +### Analyzing CSV Data + +The `results.csv` file can be imported into spreadsheet tools or analyzed with scripts: + +```bash +# Find best TPS for each target +awk -F, 'NR>1 {print $1,$5}' results.csv | sort -k2 -rn | head -3 + +# Average latency by target +awk -F, 'NR>1 {sum[$1]+=$6; count[$1]++} END {for(t in sum) print t, sum[t]/count[t]}' results.csv +``` + +## Troubleshooting + +### pgpool won't start +- Check if port 5433 is already in use: `lsof -i :5433` +- Verify config file path is correct +- Check PostgreSQL is accessible on port 5432 + +### pgbouncer authentication fails +- Ensure userlist.txt has correct SCRAM hash +- Check pgbouncer.ini has `auth_type = scram-sha-256` +- Verify PostgreSQL user exists and has correct password + +### pgbench fails with connection error +- Verify poolers are running: `ps aux | grep -E "(pgpool|pgbouncer)"` +- Test direct PostgreSQL connection first +- Check firewall settings + +### Low TPS numbers +- Ensure PostgreSQL is properly tuned +- Check system resources (CPU, memory, disk I/O) +- Verify network latency is minimal (use localhost) +- Increase shared_buffers and max_connections in postgresql.conf + +## Best Practices + +1. **Run benchmarks on dedicated hardware** to avoid interference +2. **Warm up** the database before benchmarking (run a quick test first) +3. **Run multiple iterations** and average results +4. **Monitor system resources** during tests +5. **Use consistent configuration** across all poolers +6. **Test realistic workloads** that match your production patterns +7. **Consider both average and tail latencies** (P95, P99) + +## Contributing + +To add new workloads: +1. Create a new SQL file in `workloads/` +2. Add the workload name to the `WORKLOADS` variable in run_benchmark.sh +3. Document the workload pattern + +## License + +This benchmark suite is part of the pgpool project and licensed under AGPL-3.0. diff --git a/benchmark/config/pgbouncer.ini b/benchmark/config/pgbouncer.ini new file mode 100644 index 0000000..be018ef --- /dev/null +++ b/benchmark/config/pgbouncer.ini @@ -0,0 +1,27 @@ +[databases] +postgres = host=127.0.0.1 port=5432 dbname=postgres + +[pgbouncer] +listen_addr = 127.0.0.1 +listen_port = 6432 +auth_type = scram-sha-256 +auth_file = /Users/xiaoleiliu/Code/github/everdance/pgpool/benchmark/config/userlist.txt + +; Connection pooling +pool_mode = session +max_client_conn = 200 +default_pool_size = 20 + +; Logging +admin_users = pgtest +stats_users = pgtest + +; Limits +server_lifetime = 3600 +server_idle_timeout = 600 +query_timeout = 0 + +; Logging +log_connections = 0 +log_disconnections = 0 +log_pooler_errors = 1 diff --git a/benchmark/config/pgpool.conf b/benchmark/config/pgpool.conf new file mode 100644 index 0000000..2709f96 --- /dev/null +++ b/benchmark/config/pgpool.conf @@ -0,0 +1,15 @@ +[app] +addr = localhost:5433 + +[db] +id = 1 +name = postgres +host = localhost:5432 + +[user] +dbid = 1 +name = pgtest +auth_type = scram +password = test123 +max_conn = 20 +max_clients = 200 diff --git a/benchmark/config/userlist.txt b/benchmark/config/userlist.txt new file mode 100644 index 0000000..e85b5e5 --- /dev/null +++ b/benchmark/config/userlist.txt @@ -0,0 +1 @@ +"pgtest" "scram-sha-256$4096:CHANGEME$CHANGEME" diff --git a/benchmark/scripts/cleanup.sh b/benchmark/scripts/cleanup.sh new file mode 100755 index 0000000..ff85fe0 --- /dev/null +++ b/benchmark/scripts/cleanup.sh @@ -0,0 +1,57 @@ +#!/bin/bash + +# Cleanup script for benchmark environment +# Removes test data and stops poolers + +set -e + +# Colors +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +BLUE='\033[0;34m' +NC='\033[0m' + +# Get script directory +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +BENCHMARK_DIR="$(dirname "$SCRIPT_DIR")" +PROJECT_ROOT="$(dirname "$BENCHMARK_DIR")" + +echo -e "${BLUE}=== Benchmark Cleanup ===${NC}\n" + +# Database configuration +DB_HOST="${DB_HOST:-localhost}" +DB_PORT="${DB_PORT:-5432}" +DB_USER="${DB_USER:-pgtest}" +DB_PASSWORD="${DB_PASSWORD:-test123}" +DB_NAME="${DB_NAME:-postgres}" + +# Stop pgpool if running +echo -e "${YELLOW}Stopping pgpool...${NC}" +pkill -f "pgpool.*${BENCHMARK_DIR}" || echo -e "${YELLOW}pgpool not running${NC}" + +# Stop pgbouncer if running +echo -e "${YELLOW}Stopping pgbouncer...${NC}" +pkill -f "pgbouncer.*${BENCHMARK_DIR}" || echo -e "${YELLOW}pgbouncer not running${NC}" + +# Clean up pgbench tables +echo -e "\n${YELLOW}Cleaning up pgbench tables...${NC}" +if PGPASSWORD="${DB_PASSWORD}" psql -h "${DB_HOST}" -p "${DB_PORT}" -U "${DB_USER}" -d "${DB_NAME}" \ + -c "DROP TABLE IF EXISTS pgbench_accounts, pgbench_branches, pgbench_history, pgbench_tellers CASCADE;" > /dev/null 2>&1; then + echo -e "${GREEN}✓ pgbench tables dropped${NC}" +else + echo -e "${YELLOW}⚠ Could not drop pgbench tables${NC}" +fi + +# Optionally clean up test tables +if [ "$1" = "--full" ]; then + echo -e "\n${YELLOW}Full cleanup - removing test tables...${NC}" + TEARDOWN_SQL="${PROJECT_ROOT}/test/migrations/999_teardown.sql" + if [ -f "${TEARDOWN_SQL}" ]; then + PGPASSWORD="${DB_PASSWORD}" psql -h "${DB_HOST}" -p "${DB_PORT}" -U "${DB_USER}" -d "${DB_NAME}" \ + -f "${TEARDOWN_SQL}" > /dev/null 2>&1 || true + echo -e "${GREEN}✓ Test tables cleaned up${NC}" + fi +fi + +echo -e "\n${GREEN}=== Cleanup Complete ===${NC}" diff --git a/benchmark/scripts/generate_report.sh b/benchmark/scripts/generate_report.sh new file mode 100755 index 0000000..87db921 --- /dev/null +++ b/benchmark/scripts/generate_report.sh @@ -0,0 +1,222 @@ +#!/bin/bash + +# Report generator for benchmark results +# Parses pgbench output and creates comparison tables + +set -e + +# Colors +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +BLUE='\033[0;34m' +NC='\033[0m' + +if [ $# -lt 1 ]; then + echo "Usage: $0 " + exit 1 +fi + +RESULTS_DIR="$1" + +if [ ! -d "${RESULTS_DIR}" ]; then + echo -e "${RED}Results directory not found: ${RESULTS_DIR}${NC}" + exit 1 +fi + +REPORT_FILE="${RESULTS_DIR}/report.md" +CSV_FILE="${RESULTS_DIR}/results.csv" + +echo -e "${BLUE}=== Generating Benchmark Report ===${NC}\n" +echo -e "Results directory: ${RESULTS_DIR}" +echo -e "Report file: ${REPORT_FILE}\n" + +# Function to parse pgbench output file +parse_pgbench_output() { + local file=$1 + + if [ ! -f "${file}" ]; then + echo "NA,NA,NA,NA,NA" + return + fi + + # Extract metrics + local tps=$(grep "^tps = " "${file}" | awk '{print $3}' | sed 's/[^0-9.]//g') + local latency_avg=$(grep "^latency average = " "${file}" | awk '{print $4}' | sed 's/[^0-9.]//g') + local latency_stddev=$(grep "^latency stddev = " "${file}" | awk '{print $4}' | sed 's/[^0-9.]//g') + local initial_conn=$(grep "^initial connection time = " "${file}" | awk '{print $5}' | sed 's/[^0-9.]//g') + + # Try to get percentiles + local p50=$(grep "50.000" "${file}" | tail -1 | awk '{print $NF}' | sed 's/[^0-9.]//g') + local p95=$(grep "95.000" "${file}" | tail -1 | awk '{print $NF}' | sed 's/[^0-9.]//g') + local p99=$(grep "99.000" "${file}" | tail -1 | awk '{print $NF}' | sed 's/[^0-9.]//g') + + # Default values if not found + tps=${tps:-NA} + latency_avg=${latency_avg:-NA} + latency_stddev=${latency_stddev:-NA} + p50=${p50:-NA} + p95=${p95:-NA} + p99=${p99:-NA} + initial_conn=${initial_conn:-NA} + + echo "${tps},${latency_avg},${latency_stddev},${p50},${p95},${p99},${initial_conn}" +} + +# Start markdown report +cat > "${REPORT_FILE}" << 'EOF' +# PostgreSQL Connection Pool Benchmark Report + +EOF + +# Add configuration info +if [ -f "${RESULTS_DIR}/config.txt" ]; then + echo '## Configuration' >> "${REPORT_FILE}" + echo '```' >> "${REPORT_FILE}" + cat "${RESULTS_DIR}/config.txt" >> "${REPORT_FILE}" + echo '```' >> "${REPORT_FILE}" + echo '' >> "${REPORT_FILE}" +fi + +# Start CSV file +echo "Target,Workload,Connections,Protocol,TPS,Latency_Avg_ms,Latency_Stddev_ms,P50_ms,P95_ms,P99_ms,Initial_Conn_ms" > "${CSV_FILE}" + +# Detect available targets +TARGETS="" +[ -d "${RESULTS_DIR}/direct" ] && TARGETS="${TARGETS} direct" +[ -d "${RESULTS_DIR}/pgpool" ] && TARGETS="${TARGETS} pgpool" +[ -d "${RESULTS_DIR}/pgbouncer" ] && TARGETS="${TARGETS} pgbouncer" + +# Detect workloads and connection counts from files +WORKLOADS=$(find "${RESULTS_DIR}" -name "*.log" -exec basename {} \; | cut -d_ -f1 | sort -u) +CONNECTIONS=$(find "${RESULTS_DIR}" -name "*.log" -exec basename {} \; | sed 's/.*_c\([0-9]*\)_.*/\1/' | sort -nu) +PROTOCOLS=$(find "${RESULTS_DIR}" -name "*.log" -exec basename {} \; | sed 's/.*_\([^_]*\)\.log/\1/' | sort -u) + +echo -e "${YELLOW}Found targets: ${TARGETS}${NC}" +echo -e "${YELLOW}Found workloads: ${WORKLOADS}${NC}" +echo -e "${YELLOW}Found connection counts: ${CONNECTIONS}${NC}" +echo -e "${YELLOW}Found protocols: ${PROTOCOLS}${NC}" +echo "" + +# Generate report for each workload +for workload in ${WORKLOADS}; do + echo "## Workload: ${workload}" >> "${REPORT_FILE}" + echo "" >> "${REPORT_FILE}" + + for protocol in ${PROTOCOLS}; do + echo "### Protocol: ${protocol}" >> "${REPORT_FILE}" + echo "" >> "${REPORT_FILE}" + + # TPS comparison table + echo "#### Throughput (TPS - Higher is Better)" >> "${REPORT_FILE}" + echo "" >> "${REPORT_FILE}" + echo "| Connections | $(echo ${TARGETS} | sed 's/ / | /g') |" >> "${REPORT_FILE}" + echo "|-------------|$(echo ${TARGETS} | sed 's/[^ ]*/-----------/g' | sed 's/ /|/g')|" >> "${REPORT_FILE}" + + for conn in ${CONNECTIONS}; do + row="| ${conn} " + for target in ${TARGETS}; do + file="${RESULTS_DIR}/${target}/${workload}_c${conn}_${protocol}.log" + metrics=$(parse_pgbench_output "${file}") + tps=$(echo ${metrics} | cut -d, -f1) + + # Add to CSV + echo "${target},${workload},${conn},${protocol},${metrics}" >> "${CSV_FILE}" + + row="${row}| ${tps} " + done + echo "${row}|" >> "${REPORT_FILE}" + done + echo "" >> "${REPORT_FILE}" + + # Latency comparison table + echo "#### Average Latency (ms - Lower is Better)" >> "${REPORT_FILE}" + echo "" >> "${REPORT_FILE}" + echo "| Connections | $(echo ${TARGETS} | sed 's/ / | /g') |" >> "${REPORT_FILE}" + echo "|-------------|$(echo ${TARGETS} | sed 's/[^ ]*/-----------/g' | sed 's/ /|/g')|" >> "${REPORT_FILE}" + + for conn in ${CONNECTIONS}; do + row="| ${conn} " + for target in ${TARGETS}; do + file="${RESULTS_DIR}/${target}/${workload}_c${conn}_${protocol}.log" + metrics=$(parse_pgbench_output "${file}") + latency=$(echo ${metrics} | cut -d, -f2) + row="${row}| ${latency} " + done + echo "${row}|" >> "${REPORT_FILE}" + done + echo "" >> "${REPORT_FILE}" + + # P95 latency comparison table + echo "#### P95 Latency (ms - Lower is Better)" >> "${REPORT_FILE}" + echo "" >> "${REPORT_FILE}" + echo "| Connections | $(echo ${TARGETS} | sed 's/ / | /g') |" >> "${REPORT_FILE}" + echo "|-------------|$(echo ${TARGETS} | sed 's/[^ ]*/-----------/g' | sed 's/ /|/g')|" >> "${REPORT_FILE}" + + for conn in ${CONNECTIONS}; do + row="| ${conn} " + for target in ${TARGETS}; do + file="${RESULTS_DIR}/${target}/${workload}_c${conn}_${protocol}.log" + metrics=$(parse_pgbench_output "${file}") + p95=$(echo ${metrics} | cut -d, -f5) + row="${row}| ${p95} " + done + echo "${row}|" >> "${REPORT_FILE}" + done + echo "" >> "${REPORT_FILE}" + echo "---" >> "${REPORT_FILE}" + echo "" >> "${REPORT_FILE}" + done +done + +# Add summary section +echo "## Summary" >> "${REPORT_FILE}" +echo "" >> "${REPORT_FILE}" +echo "### Winner by Category" >> "${REPORT_FILE}" +echo "" >> "${REPORT_FILE}" + +# Analyze CSV to find winners +echo "Analyzing results to find best performers..." >> "${REPORT_FILE}" +echo "" >> "${REPORT_FILE}" + +# Best overall TPS +best_tps=$(tail -n +2 "${CSV_FILE}" | sort -t, -k5 -rn | head -1) +if [ -n "${best_tps}" ]; then + target=$(echo ${best_tps} | cut -d, -f1) + workload=$(echo ${best_tps} | cut -d, -f2) + conns=$(echo ${best_tps} | cut -d, -f3) + tps=$(echo ${best_tps} | cut -d, -f5) + echo "- **Highest TPS**: ${target} (${tps} TPS with ${workload} workload, ${conns} connections)" >> "${REPORT_FILE}" +fi + +# Best average latency +best_latency=$(tail -n +2 "${CSV_FILE}" | awk -F, '$6 != "NA" {print $0}' | sort -t, -k6 -n | head -1) +if [ -n "${best_latency}" ]; then + target=$(echo ${best_latency} | cut -d, -f1) + workload=$(echo ${best_latency} | cut -d, -f2) + conns=$(echo ${best_latency} | cut -d, -f3) + latency=$(echo ${best_latency} | cut -d, -f6) + echo "- **Lowest Average Latency**: ${target} (${latency} ms with ${workload} workload, ${conns} connections)" >> "${REPORT_FILE}" +fi + +# Best P95 latency +best_p95=$(tail -n +2 "${CSV_FILE}" | awk -F, '$9 != "NA" {print $0}' | sort -t, -k9 -n | head -1) +if [ -n "${best_p95}" ]; then + target=$(echo ${best_p95} | cut -d, -f1) + workload=$(echo ${best_p95} | cut -d, -f2) + conns=$(echo ${best_p95} | cut -d, -f3) + p95=$(echo ${best_p95} | cut -d, -f9) + echo "- **Lowest P95 Latency**: ${target} (${p95} ms with ${workload} workload, ${conns} connections)" >> "${REPORT_FILE}" +fi + +echo "" >> "${REPORT_FILE}" +echo "### Raw Data" >> "${REPORT_FILE}" +echo "" >> "${REPORT_FILE}" +echo "Complete results available in: \`results.csv\`" >> "${REPORT_FILE}" + +echo -e "${GREEN}=== Report Generated ===${NC}\n" +echo -e "Markdown report: ${REPORT_FILE}" +echo -e "CSV data: ${CSV_FILE}" +echo -e "\nView report with:" +echo -e " cat ${REPORT_FILE}" +echo -e " open ${REPORT_FILE} # macOS" diff --git a/benchmark/scripts/run_benchmark.sh b/benchmark/scripts/run_benchmark.sh new file mode 100755 index 0000000..34c4de9 --- /dev/null +++ b/benchmark/scripts/run_benchmark.sh @@ -0,0 +1,228 @@ +#!/bin/bash + +# PostgreSQL Connection Pool Benchmark Runner +# Compares pgpool vs pgbouncer vs direct connection using pgbench + +set -e + +# Colors +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +BLUE='\033[0;34m' +NC='\033[0m' + +# Get script directory +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +BENCHMARK_DIR="$(dirname "$SCRIPT_DIR")" +PROJECT_ROOT="$(dirname "$BENCHMARK_DIR")" + +# Default configuration +DB_HOST="${DB_HOST:-localhost}" +DB_PORT="${DB_PORT:-5432}" +DB_USER="${DB_USER:-pgtest}" +DB_PASSWORD="${DB_PASSWORD:-test123}" +DB_NAME="${DB_NAME:-postgres}" + +PGPOOL_PORT="${PGPOOL_PORT:-5433}" +PGBOUNCER_PORT="${PGBOUNCER_PORT:-6432}" + +# Benchmark configuration +DURATION="${DURATION:-60}" +SCALE_FACTOR="${SCALE_FACTOR:-10}" +CONNECTION_COUNTS="${CONNECTION_COUNTS:-10 50 100}" +WORKLOADS="${WORKLOADS:-simple_select read_write prepared_stmt}" + +# Results directory +RESULTS_DIR="${BENCHMARK_DIR}/results" +TIMESTAMP=$(date +%Y%m%d_%H%M%S) +RUN_DIR="${RESULTS_DIR}/${TIMESTAMP}" + +echo -e "${BLUE}=== PostgreSQL Connection Pool Benchmark ===${NC}\n" + +# Create results directories +mkdir -p "${RUN_DIR}/pgpool" +mkdir -p "${RUN_DIR}/pgbouncer" +mkdir -p "${RUN_DIR}/direct" +mkdir -p "${RUN_DIR}/logs" + +# Save configuration +cat > "${RUN_DIR}/config.txt" << EOF +Benchmark Configuration +======================= +Timestamp: ${TIMESTAMP} +Duration: ${DURATION}s +Scale Factor: ${SCALE_FACTOR} +Connection Counts: ${CONNECTION_COUNTS} +Workloads: ${WORKLOADS} + +Database Configuration +====================== +DB Host: ${DB_HOST} +DB Port: ${DB_PORT} +DB Name: ${DB_NAME} +DB User: ${DB_USER} + +Pool Ports +========== +pgpool: ${PGPOOL_PORT} +pgbouncer: ${PGBOUNCER_PORT} +EOF + +echo -e "${GREEN}Results directory: ${RUN_DIR}${NC}\n" + +# Function to run pgbench test +run_pgbench() { + local target=$1 + local port=$2 + local connections=$3 + local workload=$4 + local protocol=$5 # simple, extended, or prepared + + local output_file="${RUN_DIR}/${target}/${workload}_c${connections}_${protocol}.log" + local test_name="${target} - ${workload} - c${connections} - ${protocol}" + + echo -e "${YELLOW}Running: ${test_name}${NC}" + + # Build pgbench command + local pgbench_cmd="PGPASSWORD=${DB_PASSWORD} pgbench" + pgbench_cmd+=" -h ${DB_HOST}" + pgbench_cmd+=" -p ${port}" + pgbench_cmd+=" -U ${DB_USER}" + pgbench_cmd+=" -c ${connections}" + pgbench_cmd+=" -j $(( connections > 10 ? 10 : connections ))" + pgbench_cmd+=" -T ${DURATION}" + + # Set protocol mode + case "${protocol}" in + "simple") + pgbench_cmd+=" -M simple" + ;; + "extended") + pgbench_cmd+=" -M extended" + ;; + "prepared") + pgbench_cmd+=" -M prepared" + ;; + esac + + # Set workload + if [ "${workload}" = "default" ]; then + # Use pgbench default TPC-B-like workload + pgbench_cmd+=" -b tpcb-like" + else + # Use custom workload file + local workload_file="${BENCHMARK_DIR}/workloads/${workload}.sql" + if [ ! -f "${workload_file}" ]; then + echo -e "${RED}Workload file not found: ${workload_file}${NC}" + return 1 + fi + pgbench_cmd+=" -f ${workload_file}" + fi + + pgbench_cmd+=" ${DB_NAME}" + + # Run pgbench + eval "${pgbench_cmd}" > "${output_file}" 2>&1 + + if [ $? -eq 0 ]; then + # Extract key metrics + local tps=$(grep "^tps = " "${output_file}" | awk '{print $3}') + local latency_avg=$(grep "^latency average = " "${output_file}" | awk '{print $4}') + echo -e "${GREEN}✓ Complete - TPS: ${tps}, Avg Latency: ${latency_avg}ms${NC}" + return 0 + else + echo -e "${RED}✗ Failed - check ${output_file}${NC}" + return 1 + fi +} + +# Function to check if a service is accessible +check_service() { + local name=$1 + local port=$2 + + echo -e "${YELLOW}Checking ${name} connection...${NC}" + if PGPASSWORD="${DB_PASSWORD}" psql -h "${DB_HOST}" -p "${port}" -U "${DB_USER}" -d "${DB_NAME}" -c "SELECT 1" > /dev/null 2>&1; then + echo -e "${GREEN}✓ ${name} is accessible on port ${port}${NC}" + return 0 + else + echo -e "${RED}✗ ${name} is not accessible on port ${port}${NC}" + return 1 + fi +} + +# Check all services +echo -e "${BLUE}=== Checking Services ===${NC}\n" +check_service "PostgreSQL (direct)" "${DB_PORT}" +DIRECT_AVAILABLE=$? + +check_service "pgpool" "${PGPOOL_PORT}" +PGPOOL_AVAILABLE=$? + +check_service "pgbouncer" "${PGBOUNCER_PORT}" +PGBOUNCER_AVAILABLE=$? + +echo "" + +if [ $DIRECT_AVAILABLE -ne 0 ]; then + echo -e "${RED}PostgreSQL is not accessible. Cannot proceed.${NC}" + exit 1 +fi + +# Determine which targets to test +TARGETS="" +[ $DIRECT_AVAILABLE -eq 0 ] && TARGETS="${TARGETS} direct:${DB_PORT}" +[ $PGPOOL_AVAILABLE -eq 0 ] && TARGETS="${TARGETS} pgpool:${PGPOOL_PORT}" +[ $PGBOUNCER_AVAILABLE -eq 0 ] && TARGETS="${TARGETS} pgbouncer:${PGBOUNCER_PORT}" + +echo -e "${BLUE}=== Initializing pgbench tables ===${NC}\n" +PGPASSWORD="${DB_PASSWORD}" pgbench -h "${DB_HOST}" -p "${DB_PORT}" -U "${DB_USER}" -i -s "${SCALE_FACTOR}" "${DB_NAME}" +echo "" + +# Run benchmarks +echo -e "${BLUE}=== Running Benchmarks ===${NC}\n" + +TOTAL_TESTS=0 +COMPLETED_TESTS=0 + +# Count total tests +for target_info in ${TARGETS}; do + for connections in ${CONNECTION_COUNTS}; do + for workload in ${WORKLOADS}; do + for protocol in simple extended prepared; do + TOTAL_TESTS=$((TOTAL_TESTS + 1)) + done + done + done +done + +echo -e "Total tests to run: ${TOTAL_TESTS}\n" + +# Run all test combinations +for target_info in ${TARGETS}; do + target=$(echo ${target_info} | cut -d: -f1) + port=$(echo ${target_info} | cut -d: -f2) + + echo -e "${BLUE}=== Testing: ${target} ===${NC}\n" + + for connections in ${CONNECTION_COUNTS}; do + for workload in ${WORKLOADS}; do + for protocol in simple extended prepared; do + COMPLETED_TESTS=$((COMPLETED_TESTS + 1)) + echo -e "${BLUE}[${COMPLETED_TESTS}/${TOTAL_TESTS}]${NC}" + + run_pgbench "${target}" "${port}" "${connections}" "${workload}" "${protocol}" + + # Brief pause between tests + sleep 2 + echo "" + done + done + done +done + +echo -e "${GREEN}=== Benchmark Complete ===${NC}\n" +echo -e "Results saved to: ${RUN_DIR}" +echo -e "\nTo generate comparison report, run:" +echo -e " ${SCRIPT_DIR}/generate_report.sh ${RUN_DIR}" diff --git a/benchmark/scripts/setup.sh b/benchmark/scripts/setup.sh new file mode 100755 index 0000000..e58a023 --- /dev/null +++ b/benchmark/scripts/setup.sh @@ -0,0 +1,112 @@ +#!/bin/bash + +# Setup script for benchmark environment +# This script helps set up pgpool and pgbouncer for benchmarking + +set -e + +# Colors +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +BLUE='\033[0;34m' +NC='\033[0m' + +# Get script directory +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +BENCHMARK_DIR="$(dirname "$SCRIPT_DIR")" +PROJECT_ROOT="$(dirname "$BENCHMARK_DIR")" + +echo -e "${BLUE}=== Benchmark Environment Setup ===${NC}\n" + +# Check PostgreSQL connection +echo -e "${YELLOW}1. Checking PostgreSQL connection...${NC}" +DB_HOST="${DB_HOST:-localhost}" +DB_PORT="${DB_PORT:-5432}" +DB_USER="${DB_USER:-pgtest}" +DB_PASSWORD="${DB_PASSWORD:-test123}" +DB_NAME="${DB_NAME:-postgres}" + +if PGPASSWORD="${DB_PASSWORD}" psql -h "${DB_HOST}" -p "${DB_PORT}" -U "${DB_USER}" -d "${DB_NAME}" -c "SELECT version();" > /dev/null 2>&1; then + PG_VERSION=$(PGPASSWORD="${DB_PASSWORD}" psql -h "${DB_HOST}" -p "${DB_PORT}" -U "${DB_USER}" -d "${DB_NAME}" -t -c "SELECT version();" | head -1) + echo -e "${GREEN}✓ PostgreSQL is accessible${NC}" + echo -e " ${PG_VERSION}" +else + echo -e "${RED}✗ Cannot connect to PostgreSQL${NC}" + echo -e " Please ensure PostgreSQL is running and credentials are correct:" + echo -e " Host: ${DB_HOST}:${DB_PORT}" + echo -e " User: ${DB_USER}" + echo -e " Database: ${DB_NAME}" + exit 1 +fi + +# Setup test database schema +echo -e "\n${YELLOW}2. Setting up test database schema...${NC}" +MIGRATIONS_DIR="${PROJECT_ROOT}/test/migrations" + +if [ -f "${MIGRATIONS_DIR}/001_create_test_tables.sql" ]; then + PGPASSWORD="${DB_PASSWORD}" psql -h "${DB_HOST}" -p "${DB_PORT}" -U "${DB_USER}" -d "${DB_NAME}" \ + -f "${MIGRATIONS_DIR}/001_create_test_tables.sql" > /dev/null 2>&1 + echo -e "${GREEN}✓ Test tables created${NC}" +else + echo -e "${YELLOW}⚠ Migration file not found, skipping table creation${NC}" +fi + +# Check if pgbench is installed +echo -e "\n${YELLOW}3. Checking pgbench installation...${NC}" +if command -v pgbench &> /dev/null; then + PGBENCH_VERSION=$(pgbench --version) + echo -e "${GREEN}✓ pgbench is installed${NC}" + echo -e " ${PGBENCH_VERSION}" +else + echo -e "${RED}✗ pgbench is not installed${NC}" + echo -e " Install it with: brew install postgresql (macOS) or apt-get install postgresql-client (Linux)" + exit 1 +fi + +# Check if pgpool binary exists +echo -e "\n${YELLOW}4. Checking pgpool...${NC}" +PGPOOL_BIN="${PROJECT_ROOT}/pgpool" +if [ -f "${PGPOOL_BIN}" ]; then + echo -e "${GREEN}✓ pgpool binary found${NC}" +else + echo -e "${YELLOW}⚠ pgpool binary not found${NC}" + echo -e " Building pgpool..." + cd "${PROJECT_ROOT}" + go build -o pgpool . + if [ -f "${PGPOOL_BIN}" ]; then + echo -e "${GREEN}✓ pgpool built successfully${NC}" + else + echo -e "${RED}✗ Failed to build pgpool${NC}" + exit 1 + fi +fi + +# Check if pgbouncer is installed +echo -e "\n${YELLOW}5. Checking pgbouncer...${NC}" +if command -v pgbouncer &> /dev/null; then + PGBOUNCER_VERSION=$(pgbouncer --version 2>&1 | head -1) + echo -e "${GREEN}✓ pgbouncer is installed${NC}" + echo -e " ${PGBOUNCER_VERSION}" + + # Setup pgbouncer auth file with proper SCRAM hash + echo -e "\n${YELLOW}6. Setting up pgbouncer authentication...${NC}" + echo -e "${YELLOW}Note: You need to manually update the userlist.txt file with the correct SCRAM hash${NC}" + echo -e "To generate SCRAM hash, connect to PostgreSQL and run:" + echo -e " SELECT rolpassword FROM pg_authid WHERE rolname = '${DB_USER}';" + echo -e "Then update: ${BENCHMARK_DIR}/config/userlist.txt" +else + echo -e "${YELLOW}⚠ pgbouncer is not installed${NC}" + echo -e " Install it with: brew install pgbouncer (macOS) or apt-get install pgbouncer (Linux)" + echo -e " pgbouncer is optional but recommended for comparison" +fi + +echo -e "\n${GREEN}=== Setup Complete ===${NC}\n" +echo -e "Configuration files:" +echo -e " pgpool: ${BENCHMARK_DIR}/config/pgpool.conf" +echo -e " pgbouncer: ${BENCHMARK_DIR}/config/pgbouncer.ini" +echo -e "\nTo start the poolers:" +echo -e " pgpool: ${PGPOOL_BIN} -conf ${BENCHMARK_DIR}/config/pgpool.conf" +echo -e " pgbouncer: pgbouncer -d ${BENCHMARK_DIR}/config/pgbouncer.ini" +echo -e "\nTo run benchmarks:" +echo -e " ${SCRIPT_DIR}/run_benchmark.sh" diff --git a/benchmark/workloads/complex_queries.sql b/benchmark/workloads/complex_queries.sql new file mode 100644 index 0000000..f0ea0aa --- /dev/null +++ b/benchmark/workloads/complex_queries.sql @@ -0,0 +1,26 @@ +-- Complex analytical queries +-- Used with pgbench: pgbench -f complex_queries.sql + +\set id random(1, 100) + +-- Query with JOIN +SELECT u.username, COUNT(p.id) as product_count +FROM users u +LEFT JOIN products p ON u.id % 100 = p.id % 100 +WHERE u.id > :id +GROUP BY u.username +LIMIT 20; + +-- Subquery +SELECT username, email +FROM users +WHERE id IN (SELECT id FROM users WHERE id < :id ORDER BY created_at DESC LIMIT 10); + +-- Window function +SELECT + username, + email, + ROW_NUMBER() OVER (ORDER BY created_at DESC) as row_num +FROM users +WHERE id > :id +LIMIT 20; diff --git a/benchmark/workloads/prepared_stmt.sql b/benchmark/workloads/prepared_stmt.sql new file mode 100644 index 0000000..0d1da06 --- /dev/null +++ b/benchmark/workloads/prepared_stmt.sql @@ -0,0 +1,10 @@ +-- Prepared statement workload to test statement caching +-- Used with pgbench: pgbench -f prepared_stmt.sql -M prepared + +\set id random(1, 1000) +\set userid random(1, 100) + +-- Use prepared statements +SELECT username, email FROM users WHERE id = :id; +SELECT name, price FROM products WHERE stock_quantity > :id LIMIT 10; +UPDATE users SET updated_at = CURRENT_TIMESTAMP WHERE id = :userid; diff --git a/benchmark/workloads/read_write.sql b/benchmark/workloads/read_write.sql new file mode 100644 index 0000000..cfa240e --- /dev/null +++ b/benchmark/workloads/read_write.sql @@ -0,0 +1,22 @@ +-- Mixed read-write workload +-- Used with pgbench: pgbench -f read_write.sql + +\set id random(1, 1000) +\set r random(1, 100) + +BEGIN; + +-- 70% reads +\if :r <= 70 +SELECT username, email FROM users WHERE id = :id; +\elif :r <= 85 +-- 15% updates +UPDATE users SET updated_at = CURRENT_TIMESTAMP WHERE id = :id; +\else +-- 15% inserts +INSERT INTO users (username, email) +VALUES ('bench_' || :id, 'bench_' || :id || '@test.com') +ON CONFLICT (username) DO UPDATE SET updated_at = CURRENT_TIMESTAMP; +\endif + +COMMIT; diff --git a/benchmark/workloads/simple_select.sql b/benchmark/workloads/simple_select.sql new file mode 100644 index 0000000..572d936 --- /dev/null +++ b/benchmark/workloads/simple_select.sql @@ -0,0 +1,5 @@ +-- Simple SELECT queries for read-only workload +-- Used with pgbench: pgbench -f simple_select.sql + +\set id random(1, 1000) +SELECT username, email FROM users WHERE id = :id; From 8d2afaac867b79185910fe3cec9dd613159b4c13 Mon Sep 17 00:00:00 2001 From: xiaolei Date: Wed, 5 Nov 2025 15:29:15 -0500 Subject: [PATCH 05/17] benchmark tune --- benchmark/README.md | 46 +++++++------------ benchmark/config/pgbouncer.ini | 2 +- benchmark/config/userlist.txt | 2 +- benchmark/scripts/cleanup.sh | 11 ----- benchmark/scripts/run_benchmark.sh | 59 +++++++++---------------- benchmark/scripts/setup.sh | 20 ++------- benchmark/workloads/complex_queries.sql | 26 ----------- benchmark/workloads/prepared_stmt.sql | 10 ----- benchmark/workloads/read_write.sql | 22 --------- benchmark/workloads/simple_select.sql | 5 --- 10 files changed, 42 insertions(+), 161 deletions(-) delete mode 100644 benchmark/workloads/complex_queries.sql delete mode 100644 benchmark/workloads/prepared_stmt.sql delete mode 100644 benchmark/workloads/read_write.sql delete mode 100644 benchmark/workloads/simple_select.sql diff --git a/benchmark/README.md b/benchmark/README.md index 67b890a..1d30cad 100644 --- a/benchmark/README.md +++ b/benchmark/README.md @@ -19,11 +19,6 @@ benchmark/ │ ├── pgpool.conf # pgpool configuration │ ├── pgbouncer.ini # pgbouncer configuration │ └── userlist.txt # pgbouncer auth file -├── workloads/ # SQL workload files -│ ├── simple_select.sql -│ ├── read_write.sql -│ ├── prepared_stmt.sql -│ └── complex_queries.sql ├── scripts/ # Benchmark scripts │ ├── setup.sh # Environment setup │ ├── run_benchmark.sh # Main benchmark runner @@ -65,7 +60,6 @@ cd benchmark This will: - Check PostgreSQL connectivity -- Create test database schema - Verify pgbench installation - Build pgpool binary if needed - Check pgbouncer availability @@ -134,7 +128,7 @@ pgbouncer -d benchmark/config/pgbouncer.ini Default settings: - Duration: 60 seconds per test - Connections: 10, 50, 100 -- Workloads: simple_select, read_write, prepared_stmt +- Workload: pgbench default TPC-B-like workload - Protocols: simple, extended, prepared ### 5. Generate Report @@ -169,7 +163,6 @@ export PGBOUNCER_PORT=6432 export DURATION=60 # seconds per test export SCALE_FACTOR=10 # pgbench scale factor export CONNECTION_COUNTS="10 50 100 200" # connection counts to test -export WORKLOADS="simple_select read_write" # workloads to test ``` ### Custom Benchmark Run @@ -181,26 +174,20 @@ DURATION=30 CONNECTION_COUNTS="10 50" ./scripts/run_benchmark.sh # Heavy load test (120s, many connections) DURATION=120 CONNECTION_COUNTS="50 100 200 500" ./scripts/run_benchmark.sh -# Test only read workloads -WORKLOADS="simple_select" ./scripts/run_benchmark.sh +# Test with larger scale factor (more data) +SCALE_FACTOR=100 ./scripts/run_benchmark.sh ``` -## Workload Descriptions +## Workload Description -### simple_select.sql -Pure read workload. Tests SELECT query performance. -```sql -SELECT username, email FROM users WHERE id = :id; -``` - -### read_write.sql -Mixed workload (70% reads, 15% updates, 15% inserts). Tests real-world transaction patterns. +The benchmark uses **pgbench's default TPC-B-like workload**, which is the industry-standard benchmark for PostgreSQL performance testing. This workload: -### prepared_stmt.sql -Tests prepared statement caching and reuse across connections. +- Simulates a banking/teller application with account updates and balance checks +- Includes multiple tables: `pgbench_accounts`, `pgbench_branches`, `pgbench_tellers`, `pgbench_history` +- Performs a mix of SELECT, UPDATE, and INSERT operations in each transaction +- Provides consistent, reproducible results for comparing different connection pooling solutions -### complex_queries.sql -Analytical queries with JOINs, subqueries, and window functions. +The TPC-B workload is automatically initialized by pgbench with the specified scale factor, eliminating the need for custom migration scripts. ## Understanding Results @@ -226,7 +213,7 @@ Analytical queries with JOINs, subqueries, and window functions. ### Sample Report Output ```markdown -## Workload: simple_select +## Workload: tpcb ### Protocol: extended @@ -252,9 +239,6 @@ Analytical queries with JOINs, subqueries, and window functions. ```bash # Stop poolers and clean pgbench tables ./scripts/cleanup.sh - -# Full cleanup (removes all test data) -./scripts/cleanup.sh --full ``` ## Advanced Usage @@ -342,10 +326,10 @@ awk -F, 'NR>1 {sum[$1]+=$6; count[$1]++} END {for(t in sum) print t, sum[t]/coun ## Contributing -To add new workloads: -1. Create a new SQL file in `workloads/` -2. Add the workload name to the `WORKLOADS` variable in run_benchmark.sh -3. Document the workload pattern +The benchmark suite uses pgbench's default TPC-B-like workload. If you need to test custom workloads, you can: +1. Create SQL files with pgbench-compatible syntax +2. Modify `run_benchmark.sh` to reference your custom workload files +3. Use pgbench variable syntax (e.g., `\set id random(1, 1000)`) ## License diff --git a/benchmark/config/pgbouncer.ini b/benchmark/config/pgbouncer.ini index be018ef..ecd1c1b 100644 --- a/benchmark/config/pgbouncer.ini +++ b/benchmark/config/pgbouncer.ini @@ -8,7 +8,7 @@ auth_type = scram-sha-256 auth_file = /Users/xiaoleiliu/Code/github/everdance/pgpool/benchmark/config/userlist.txt ; Connection pooling -pool_mode = session +pool_mode = transaction max_client_conn = 200 default_pool_size = 20 diff --git a/benchmark/config/userlist.txt b/benchmark/config/userlist.txt index e85b5e5..d28317f 100644 --- a/benchmark/config/userlist.txt +++ b/benchmark/config/userlist.txt @@ -1 +1 @@ -"pgtest" "scram-sha-256$4096:CHANGEME$CHANGEME" +"pgtest" "test123" diff --git a/benchmark/scripts/cleanup.sh b/benchmark/scripts/cleanup.sh index ff85fe0..06bb2b0 100755 --- a/benchmark/scripts/cleanup.sh +++ b/benchmark/scripts/cleanup.sh @@ -43,15 +43,4 @@ else echo -e "${YELLOW}⚠ Could not drop pgbench tables${NC}" fi -# Optionally clean up test tables -if [ "$1" = "--full" ]; then - echo -e "\n${YELLOW}Full cleanup - removing test tables...${NC}" - TEARDOWN_SQL="${PROJECT_ROOT}/test/migrations/999_teardown.sql" - if [ -f "${TEARDOWN_SQL}" ]; then - PGPASSWORD="${DB_PASSWORD}" psql -h "${DB_HOST}" -p "${DB_PORT}" -U "${DB_USER}" -d "${DB_NAME}" \ - -f "${TEARDOWN_SQL}" > /dev/null 2>&1 || true - echo -e "${GREEN}✓ Test tables cleaned up${NC}" - fi -fi - echo -e "\n${GREEN}=== Cleanup Complete ===${NC}" diff --git a/benchmark/scripts/run_benchmark.sh b/benchmark/scripts/run_benchmark.sh index 34c4de9..c8c8b0b 100755 --- a/benchmark/scripts/run_benchmark.sh +++ b/benchmark/scripts/run_benchmark.sh @@ -31,7 +31,6 @@ PGBOUNCER_PORT="${PGBOUNCER_PORT:-6432}" DURATION="${DURATION:-60}" SCALE_FACTOR="${SCALE_FACTOR:-10}" CONNECTION_COUNTS="${CONNECTION_COUNTS:-10 50 100}" -WORKLOADS="${WORKLOADS:-simple_select read_write prepared_stmt}" # Results directory RESULTS_DIR="${BENCHMARK_DIR}/results" @@ -54,7 +53,7 @@ Timestamp: ${TIMESTAMP} Duration: ${DURATION}s Scale Factor: ${SCALE_FACTOR} Connection Counts: ${CONNECTION_COUNTS} -Workloads: ${WORKLOADS} +Workload: TPC-B-like (pgbench default) Database Configuration ====================== @@ -76,11 +75,10 @@ run_pgbench() { local target=$1 local port=$2 local connections=$3 - local workload=$4 - local protocol=$5 # simple, extended, or prepared + local protocol=$4 # simple, extended, or prepared - local output_file="${RUN_DIR}/${target}/${workload}_c${connections}_${protocol}.log" - local test_name="${target} - ${workload} - c${connections} - ${protocol}" + local output_file="${RUN_DIR}/${target}/tpcb_c${connections}_${protocol}.log" + local test_name="${target} - TPC-B - c${connections} - ${protocol}" echo -e "${YELLOW}Running: ${test_name}${NC}" @@ -106,19 +104,8 @@ run_pgbench() { ;; esac - # Set workload - if [ "${workload}" = "default" ]; then - # Use pgbench default TPC-B-like workload - pgbench_cmd+=" -b tpcb-like" - else - # Use custom workload file - local workload_file="${BENCHMARK_DIR}/workloads/${workload}.sql" - if [ ! -f "${workload_file}" ]; then - echo -e "${RED}Workload file not found: ${workload_file}${NC}" - return 1 - fi - pgbench_cmd+=" -f ${workload_file}" - fi + # Set workload (default: TPC-B-like) + pgbench_cmd+=" -b tpcb-like" pgbench_cmd+=" ${DB_NAME}" @@ -171,10 +158,10 @@ if [ $DIRECT_AVAILABLE -ne 0 ]; then fi # Determine which targets to test -TARGETS="" -[ $DIRECT_AVAILABLE -eq 0 ] && TARGETS="${TARGETS} direct:${DB_PORT}" -[ $PGPOOL_AVAILABLE -eq 0 ] && TARGETS="${TARGETS} pgpool:${PGPOOL_PORT}" -[ $PGBOUNCER_AVAILABLE -eq 0 ] && TARGETS="${TARGETS} pgbouncer:${PGBOUNCER_PORT}" +TARGETS=() +[ $DIRECT_AVAILABLE -eq 0 ] && TARGETS+=("direct:${DB_PORT}") +[ $PGPOOL_AVAILABLE -eq 0 ] && TARGETS+=("pgpool:${PGPOOL_PORT}") +[ $PGBOUNCER_AVAILABLE -eq 0 ] && TARGETS+=("pgbouncer:${PGBOUNCER_PORT}") echo -e "${BLUE}=== Initializing pgbench tables ===${NC}\n" PGPASSWORD="${DB_PASSWORD}" pgbench -h "${DB_HOST}" -p "${DB_PORT}" -U "${DB_USER}" -i -s "${SCALE_FACTOR}" "${DB_NAME}" @@ -187,12 +174,10 @@ TOTAL_TESTS=0 COMPLETED_TESTS=0 # Count total tests -for target_info in ${TARGETS}; do +for target_info in "${TARGETS[@]}"; do for connections in ${CONNECTION_COUNTS}; do - for workload in ${WORKLOADS}; do - for protocol in simple extended prepared; do - TOTAL_TESTS=$((TOTAL_TESTS + 1)) - done + for protocol in simple extended prepared; do + TOTAL_TESTS=$((TOTAL_TESTS + 1)) done done done @@ -200,24 +185,22 @@ done echo -e "Total tests to run: ${TOTAL_TESTS}\n" # Run all test combinations -for target_info in ${TARGETS}; do +for target_info in "${TARGETS[@]}"; do target=$(echo ${target_info} | cut -d: -f1) port=$(echo ${target_info} | cut -d: -f2) echo -e "${BLUE}=== Testing: ${target} ===${NC}\n" for connections in ${CONNECTION_COUNTS}; do - for workload in ${WORKLOADS}; do - for protocol in simple extended prepared; do - COMPLETED_TESTS=$((COMPLETED_TESTS + 1)) - echo -e "${BLUE}[${COMPLETED_TESTS}/${TOTAL_TESTS}]${NC}" + for protocol in simple extended prepared; do + COMPLETED_TESTS=$((COMPLETED_TESTS + 1)) + echo -e "${BLUE}[${COMPLETED_TESTS}/${TOTAL_TESTS}]${NC}" - run_pgbench "${target}" "${port}" "${connections}" "${workload}" "${protocol}" + run_pgbench "${target}" "${port}" "${connections}" "${protocol}" - # Brief pause between tests - sleep 2 - echo "" - done + # Brief pause between tests + sleep 2 + echo "" done done done diff --git a/benchmark/scripts/setup.sh b/benchmark/scripts/setup.sh index e58a023..61e27b0 100755 --- a/benchmark/scripts/setup.sh +++ b/benchmark/scripts/setup.sh @@ -40,20 +40,8 @@ else exit 1 fi -# Setup test database schema -echo -e "\n${YELLOW}2. Setting up test database schema...${NC}" -MIGRATIONS_DIR="${PROJECT_ROOT}/test/migrations" - -if [ -f "${MIGRATIONS_DIR}/001_create_test_tables.sql" ]; then - PGPASSWORD="${DB_PASSWORD}" psql -h "${DB_HOST}" -p "${DB_PORT}" -U "${DB_USER}" -d "${DB_NAME}" \ - -f "${MIGRATIONS_DIR}/001_create_test_tables.sql" > /dev/null 2>&1 - echo -e "${GREEN}✓ Test tables created${NC}" -else - echo -e "${YELLOW}⚠ Migration file not found, skipping table creation${NC}" -fi - # Check if pgbench is installed -echo -e "\n${YELLOW}3. Checking pgbench installation...${NC}" +echo -e "\n${YELLOW}2. Checking pgbench installation...${NC}" if command -v pgbench &> /dev/null; then PGBENCH_VERSION=$(pgbench --version) echo -e "${GREEN}✓ pgbench is installed${NC}" @@ -65,7 +53,7 @@ else fi # Check if pgpool binary exists -echo -e "\n${YELLOW}4. Checking pgpool...${NC}" +echo -e "\n${YELLOW}3. Checking pgpool...${NC}" PGPOOL_BIN="${PROJECT_ROOT}/pgpool" if [ -f "${PGPOOL_BIN}" ]; then echo -e "${GREEN}✓ pgpool binary found${NC}" @@ -83,14 +71,14 @@ else fi # Check if pgbouncer is installed -echo -e "\n${YELLOW}5. Checking pgbouncer...${NC}" +echo -e "\n${YELLOW}4. Checking pgbouncer...${NC}" if command -v pgbouncer &> /dev/null; then PGBOUNCER_VERSION=$(pgbouncer --version 2>&1 | head -1) echo -e "${GREEN}✓ pgbouncer is installed${NC}" echo -e " ${PGBOUNCER_VERSION}" # Setup pgbouncer auth file with proper SCRAM hash - echo -e "\n${YELLOW}6. Setting up pgbouncer authentication...${NC}" + echo -e "\n${YELLOW}5. Setting up pgbouncer authentication...${NC}" echo -e "${YELLOW}Note: You need to manually update the userlist.txt file with the correct SCRAM hash${NC}" echo -e "To generate SCRAM hash, connect to PostgreSQL and run:" echo -e " SELECT rolpassword FROM pg_authid WHERE rolname = '${DB_USER}';" diff --git a/benchmark/workloads/complex_queries.sql b/benchmark/workloads/complex_queries.sql deleted file mode 100644 index f0ea0aa..0000000 --- a/benchmark/workloads/complex_queries.sql +++ /dev/null @@ -1,26 +0,0 @@ --- Complex analytical queries --- Used with pgbench: pgbench -f complex_queries.sql - -\set id random(1, 100) - --- Query with JOIN -SELECT u.username, COUNT(p.id) as product_count -FROM users u -LEFT JOIN products p ON u.id % 100 = p.id % 100 -WHERE u.id > :id -GROUP BY u.username -LIMIT 20; - --- Subquery -SELECT username, email -FROM users -WHERE id IN (SELECT id FROM users WHERE id < :id ORDER BY created_at DESC LIMIT 10); - --- Window function -SELECT - username, - email, - ROW_NUMBER() OVER (ORDER BY created_at DESC) as row_num -FROM users -WHERE id > :id -LIMIT 20; diff --git a/benchmark/workloads/prepared_stmt.sql b/benchmark/workloads/prepared_stmt.sql deleted file mode 100644 index 0d1da06..0000000 --- a/benchmark/workloads/prepared_stmt.sql +++ /dev/null @@ -1,10 +0,0 @@ --- Prepared statement workload to test statement caching --- Used with pgbench: pgbench -f prepared_stmt.sql -M prepared - -\set id random(1, 1000) -\set userid random(1, 100) - --- Use prepared statements -SELECT username, email FROM users WHERE id = :id; -SELECT name, price FROM products WHERE stock_quantity > :id LIMIT 10; -UPDATE users SET updated_at = CURRENT_TIMESTAMP WHERE id = :userid; diff --git a/benchmark/workloads/read_write.sql b/benchmark/workloads/read_write.sql deleted file mode 100644 index cfa240e..0000000 --- a/benchmark/workloads/read_write.sql +++ /dev/null @@ -1,22 +0,0 @@ --- Mixed read-write workload --- Used with pgbench: pgbench -f read_write.sql - -\set id random(1, 1000) -\set r random(1, 100) - -BEGIN; - --- 70% reads -\if :r <= 70 -SELECT username, email FROM users WHERE id = :id; -\elif :r <= 85 --- 15% updates -UPDATE users SET updated_at = CURRENT_TIMESTAMP WHERE id = :id; -\else --- 15% inserts -INSERT INTO users (username, email) -VALUES ('bench_' || :id, 'bench_' || :id || '@test.com') -ON CONFLICT (username) DO UPDATE SET updated_at = CURRENT_TIMESTAMP; -\endif - -COMMIT; diff --git a/benchmark/workloads/simple_select.sql b/benchmark/workloads/simple_select.sql deleted file mode 100644 index 572d936..0000000 --- a/benchmark/workloads/simple_select.sql +++ /dev/null @@ -1,5 +0,0 @@ --- Simple SELECT queries for read-only workload --- Used with pgbench: pgbench -f simple_select.sql - -\set id random(1, 1000) -SELECT username, email FROM users WHERE id = :id; From 42a5752b55d85b6a6fcbbf3f9256fdff841dc3f6 Mon Sep 17 00:00:00 2001 From: xiaolei Date: Wed, 5 Nov 2025 15:31:04 -0500 Subject: [PATCH 06/17] ignore benchmark results --- .gitignore | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index fede587..5da0483 100644 --- a/.gitignore +++ b/.gitignore @@ -2,4 +2,5 @@ pgpool vendor test/vendor -test/output \ No newline at end of file +test/output +benchmark/results \ No newline at end of file From 6ef61f04dd26f59cb8e27cb33cbf6da0e2f5fc02 Mon Sep 17 00:00:00 2001 From: xiaolei Date: Tue, 11 Nov 2025 11:57:57 -0500 Subject: [PATCH 07/17] fix tx handle --- benchmark/scripts/run_benchmark.sh | 6 +++--- pool/client.go | 1 + pool/server.go | 6 ++++-- 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/benchmark/scripts/run_benchmark.sh b/benchmark/scripts/run_benchmark.sh index c8c8b0b..5a98ea2 100755 --- a/benchmark/scripts/run_benchmark.sh +++ b/benchmark/scripts/run_benchmark.sh @@ -29,8 +29,8 @@ PGBOUNCER_PORT="${PGBOUNCER_PORT:-6432}" # Benchmark configuration DURATION="${DURATION:-60}" -SCALE_FACTOR="${SCALE_FACTOR:-10}" -CONNECTION_COUNTS="${CONNECTION_COUNTS:-10 50 100}" +SCALE_FACTOR="${SCALE_FACTOR:-1}" +CONNECTION_COUNTS="${CONNECTION_COUNTS:-10}" # Results directory RESULTS_DIR="${BENCHMARK_DIR}/results" @@ -192,7 +192,7 @@ for target_info in "${TARGETS[@]}"; do echo -e "${BLUE}=== Testing: ${target} ===${NC}\n" for connections in ${CONNECTION_COUNTS}; do - for protocol in simple extended prepared; do + for protocol in simple ; do #extended prepared; do COMPLETED_TESTS=$((COMPLETED_TESTS + 1)) echo -e "${BLUE}[${COMPLETED_TESTS}/${TOTAL_TESTS}]${NC}" diff --git a/pool/client.go b/pool/client.go index 297d73d..7609736 100644 --- a/pool/client.go +++ b/pool/client.go @@ -30,6 +30,7 @@ const ( ServerConnection WaitType = iota ServerParse ServerSyncReady + ServerSyncInTx ServerCopyResp ) diff --git a/pool/server.go b/pool/server.go index c269ebe..5f2caab 100644 --- a/pool/server.go +++ b/pool/server.go @@ -88,8 +88,10 @@ func (p *Pool) handleServer(sc *ServConn) { if sc.Client != nil { _ = sc.Client.Write(m) msg := m.(*proto.ReadyQuery) - if msg.State == 'I' { - if sc.Client.State == ClientSyncWait { + if sc.Client.State == ClientSyncWait { + if msg.State == 'T' { + sc.Client.Wait <- ServerSyncInTx + } else { sc.Client.Wait <- ServerSyncReady <-sc.Wait } From 07af10b5da6f621722b5f7e76b08282e8d4e6dff Mon Sep 17 00:00:00 2001 From: xiaolei Date: Tue, 11 Nov 2025 13:34:04 -0500 Subject: [PATCH 08/17] fix smoke test --- .gitignore | 2 +- test/run_smoke.sh | 65 ++++------------------------------------------- 2 files changed, 6 insertions(+), 61 deletions(-) diff --git a/.gitignore b/.gitignore index 5da0483..a173dd3 100644 --- a/.gitignore +++ b/.gitignore @@ -2,5 +2,5 @@ pgpool vendor test/vendor -test/output +test/*.out benchmark/results \ No newline at end of file diff --git a/test/run_smoke.sh b/test/run_smoke.sh index 4e6fd06..937c848 100755 --- a/test/run_smoke.sh +++ b/test/run_smoke.sh @@ -82,12 +82,7 @@ else fi echo "" -# Create output directories -OUTPUT_DIR="${SCRIPT_DIR}/output" -mkdir -p "${OUTPUT_DIR}" - -ACTUAL_OUTPUT="${OUTPUT_DIR}/smoke_test_actual.out" -EXPECTED_OUTPUT="${SCRIPT_DIR}/smoke_test_expected.out" +OUTPUT="${SCRIPT_DIR}/smoke_test.out" # Run the smoke test echo -e "${YELLOW}Running smoke test suite...${NC}" @@ -95,61 +90,11 @@ echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━ echo "" # Run test and capture output -PGPASSWORD="${DB_PASSWORD}" psql -h "${TARGET_HOST}" -p "${TARGET_PORT}" -U "${DB_USER}" -d "${DB_NAME}" -f "${SCRIPT_DIR}/smoke_test.sql" > "${ACTUAL_OUTPUT}" 2>&1 - -# Display the output to the user -cat "${ACTUAL_OUTPUT}" - -echo "" -echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}" -echo "" +PGPASSWORD="${DB_PASSWORD}" psql -h "${TARGET_HOST}" -p "${TARGET_PORT}" -U "${DB_USER}" -d "${DB_NAME}" -f "${SCRIPT_DIR}/smoke_test.sql" > "${OUTPUT}" 2>&1 -# Check for ERROR or FATAL in output -if grep -i -E "(ERROR|FATAL)" "${ACTUAL_OUTPUT}" > /dev/null 2>&1; then - echo -e "${RED}✗ Smoke test output contains errors:${NC}" - grep -i -E "(ERROR|FATAL)" "${ACTUAL_OUTPUT}" - exit 1 -fi - -# If expected output exists, compare against it -if [ -f "${EXPECTED_OUTPUT}" ]; then - echo -e "${YELLOW}Comparing output against expected baseline...${NC}" - - # Normalize outputs by removing dynamic values - normalize_output() { - sed -E \ - -e 's/[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}(\.[0-9]+)?(\+[0-9]{2})?/TIMESTAMP/g' \ - -e 's/\| +[0-9]+ \|/| ID |/g' \ - -e 's/backend_pid +\| +[0-9]+/backend_pid | PID/g' \ - -e 's/current_transaction_id +\| +[0-9]+/current_transaction_id | TXID/g' \ - -e 's/server_ip +\| +[0-9.]+/server_ip | IP/g' \ - -e 's/server_port +\| +[0-9]+/server_port | PORT/g' \ - -e 's/\b[0-9]+\.[0-9]+\b/NUM/g' \ - "$1" - } - - NORMALIZED_ACTUAL="${OUTPUT_DIR}/normalized_actual.out" - NORMALIZED_EXPECTED="${OUTPUT_DIR}/normalized_expected.out" - - normalize_output "${ACTUAL_OUTPUT}" > "${NORMALIZED_ACTUAL}" - normalize_output "${EXPECTED_OUTPUT}" > "${NORMALIZED_EXPECTED}" - - if diff -u "${NORMALIZED_EXPECTED}" "${NORMALIZED_ACTUAL}" > "${OUTPUT_DIR}/diff.out"; then - echo -e "${GREEN}✓ Output matches expected baseline${NC}" - else - echo -e "${RED}✗ Output differs from expected baseline${NC}" - echo "" - echo -e "${YELLOW}Diff (expected vs actual):${NC}" - head -n 50 "${OUTPUT_DIR}/diff.out" - if [ $(wc -l < "${OUTPUT_DIR}/diff.out") -gt 50 ]; then - echo "... (diff truncated, see ${OUTPUT_DIR}/diff.out for full output)" - fi - exit 1 - fi +if [ $? -ne 0 ]; then + echo -e "${YELLOW}test failed:${NC}" + tail "${OUTPUT}" else - echo -e "${YELLOW}⚠ No expected output baseline found at ${EXPECTED_OUTPUT}${NC}" - echo -e "${YELLOW} To create a baseline, run:${NC}" - echo -e "${YELLOW} cp ${ACTUAL_OUTPUT} ${EXPECTED_OUTPUT}${NC}" - echo "" echo -e "${GREEN}✓ Test executed successfully (no errors found)${NC}" fi From 9b25d9eaa0c72aab1f119713e30b9b91894b75de Mon Sep 17 00:00:00 2001 From: xiaolei Date: Wed, 12 Nov 2025 09:04:58 -0500 Subject: [PATCH 09/17] fix test --- proto/reader_test.go | 2 +- test/{concurrent_test.go => concurrent.go} | 0 test/run_concurrent.sh | 2 +- 3 files changed, 2 insertions(+), 2 deletions(-) rename test/{concurrent_test.go => concurrent.go} (100%) diff --git a/proto/reader_test.go b/proto/reader_test.go index 6d6f8a2..93758e8 100644 --- a/proto/reader_test.go +++ b/proto/reader_test.go @@ -80,7 +80,7 @@ func TestMessageReaderLen(t *testing.T) { func TestMessageReaderRewind(t *testing.T) { reader := &MessageReader{ - buffer: [bufSize]byte{}, + buffer: make([]byte, bufSize), read: 100, write: 150, } diff --git a/test/concurrent_test.go b/test/concurrent.go similarity index 100% rename from test/concurrent_test.go rename to test/concurrent.go diff --git a/test/run_concurrent.sh b/test/run_concurrent.sh index b2c5701..3d3f32f 100755 --- a/test/run_concurrent.sh +++ b/test/run_concurrent.sh @@ -102,7 +102,7 @@ cd "${SCRIPT_DIR}" DB_CONNECTION_STRING="postgres://${DB_USER}:${DB_PASSWORD}@${PGPOOL_HOST}:${PGPOOL_PORT}/${DB_NAME}" \ NUM_CONNECTIONS="${NUM_CONNECTIONS}" \ QUERIES_PER_CONNECTION="${QUERIES_PER_CONNECTION}" \ -go run concurrent_test.go +go run concurrent.go if [ $? -eq 0 ]; then echo -e "\n${GREEN}✓ Concurrent tests passed${NC}" From 63e1412e2781fabafe0e8e0247743f6fb47d4c83 Mon Sep 17 00:00:00 2001 From: xiaolei Date: Wed, 12 Nov 2025 09:07:19 -0500 Subject: [PATCH 10/17] lint --- proto/reader.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/proto/reader.go b/proto/reader.go index 86a7ab1..2b2006e 100644 --- a/proto/reader.go +++ b/proto/reader.go @@ -40,7 +40,7 @@ func (m *MessageReader) rewind(nread int) { return } - copy(m.buffer[:], m.buffer[m.read:]) + copy(m.buffer, m.buffer[m.read:]) m.write -= m.read m.read = 0 } From 6ddd4a2e08f1e205434fa1c852d52c44450e45b0 Mon Sep 17 00:00:00 2001 From: xiaolei Date: Fri, 14 Nov 2025 11:23:50 -0500 Subject: [PATCH 11/17] tidy --- benchmark/config/pgbouncer.ini | 2 +- benchmark/scripts/run_benchmark.sh | 64 ++++++++++++++---------------- 2 files changed, 30 insertions(+), 36 deletions(-) diff --git a/benchmark/config/pgbouncer.ini b/benchmark/config/pgbouncer.ini index ecd1c1b..f7773d3 100644 --- a/benchmark/config/pgbouncer.ini +++ b/benchmark/config/pgbouncer.ini @@ -5,7 +5,7 @@ postgres = host=127.0.0.1 port=5432 dbname=postgres listen_addr = 127.0.0.1 listen_port = 6432 auth_type = scram-sha-256 -auth_file = /Users/xiaoleiliu/Code/github/everdance/pgpool/benchmark/config/userlist.txt +auth_file = userlist.txt ; Connection pooling pool_mode = transaction diff --git a/benchmark/scripts/run_benchmark.sh b/benchmark/scripts/run_benchmark.sh index 5a98ea2..b07a2f6 100755 --- a/benchmark/scripts/run_benchmark.sh +++ b/benchmark/scripts/run_benchmark.sh @@ -24,13 +24,16 @@ DB_USER="${DB_USER:-pgtest}" DB_PASSWORD="${DB_PASSWORD:-test123}" DB_NAME="${DB_NAME:-postgres}" +PGPOOL_HOST="${PGPOOL_HOST:-localhost}" PGPOOL_PORT="${PGPOOL_PORT:-5433}" +PGBOUNCER_HOST="${PGBOUNCER_HOST:-localhost}" PGBOUNCER_PORT="${PGBOUNCER_PORT:-6432}" # Benchmark configuration DURATION="${DURATION:-60}" SCALE_FACTOR="${SCALE_FACTOR:-1}" -CONNECTION_COUNTS="${CONNECTION_COUNTS:-10}" +CONNECTION_COUNTS="${CONNECTION_COUNTS:-10 50}" +PROTOCOLS=("simple" "extended" "prepared") # Results directory RESULTS_DIR="${BENCHMARK_DIR}/results" @@ -62,10 +65,10 @@ DB Port: ${DB_PORT} DB Name: ${DB_NAME} DB User: ${DB_USER} -Pool Ports +Pool Configuration ========== -pgpool: ${PGPOOL_PORT} -pgbouncer: ${PGBOUNCER_PORT} +pgpool: ${PGPOOL_HOST} ${PGPOOL_PORT} +pgbouncer: ${PGBOUNCER_HOST} ${PGBOUNCER_PORT} EOF echo -e "${GREEN}Results directory: ${RUN_DIR}${NC}\n" @@ -73,9 +76,10 @@ echo -e "${GREEN}Results directory: ${RUN_DIR}${NC}\n" # Function to run pgbench test run_pgbench() { local target=$1 - local port=$2 - local connections=$3 - local protocol=$4 # simple, extended, or prepared + local host=$2 + local port=$3 + local connections=$4 + local protocol=$5 # simple, extended, or prepared local output_file="${RUN_DIR}/${target}/tpcb_c${connections}_${protocol}.log" local test_name="${target} - TPC-B - c${connections} - ${protocol}" @@ -84,25 +88,13 @@ run_pgbench() { # Build pgbench command local pgbench_cmd="PGPASSWORD=${DB_PASSWORD} pgbench" - pgbench_cmd+=" -h ${DB_HOST}" + pgbench_cmd+=" -h ${host}" pgbench_cmd+=" -p ${port}" pgbench_cmd+=" -U ${DB_USER}" pgbench_cmd+=" -c ${connections}" pgbench_cmd+=" -j $(( connections > 10 ? 10 : connections ))" pgbench_cmd+=" -T ${DURATION}" - - # Set protocol mode - case "${protocol}" in - "simple") - pgbench_cmd+=" -M simple" - ;; - "extended") - pgbench_cmd+=" -M extended" - ;; - "prepared") - pgbench_cmd+=" -M prepared" - ;; - esac + pgbench_cmd+=" -M ${protocol}" # Set workload (default: TPC-B-like) pgbench_cmd+=" -b tpcb-like" @@ -127,27 +119,28 @@ run_pgbench() { # Function to check if a service is accessible check_service() { local name=$1 - local port=$2 + local host=$2 + local port=$3 echo -e "${YELLOW}Checking ${name} connection...${NC}" - if PGPASSWORD="${DB_PASSWORD}" psql -h "${DB_HOST}" -p "${port}" -U "${DB_USER}" -d "${DB_NAME}" -c "SELECT 1" > /dev/null 2>&1; then - echo -e "${GREEN}✓ ${name} is accessible on port ${port}${NC}" + if PGPASSWORD="${DB_PASSWORD}" psql -h "${host}" -p "${port}" -U "${DB_USER}" -d "${DB_NAME}" -c "SELECT 1" > /dev/null 2>&1; then + echo -e "${GREEN}✓ ${name} is accessible on ${host}:${port}${NC}" return 0 else - echo -e "${RED}✗ ${name} is not accessible on port ${port}${NC}" + echo -e "${RED}✗ ${name} is not accessible on ${host}:${port}${NC}" return 1 fi } # Check all services echo -e "${BLUE}=== Checking Services ===${NC}\n" -check_service "PostgreSQL (direct)" "${DB_PORT}" +check_service "PostgreSQL (direct)" "${DB_HOST}" "${DB_PORT}" DIRECT_AVAILABLE=$? -check_service "pgpool" "${PGPOOL_PORT}" +check_service "pgpool" "${PGPOOL_HOST}" "${PGPOOL_PORT}" PGPOOL_AVAILABLE=$? -check_service "pgbouncer" "${PGBOUNCER_PORT}" +check_service "pgbouncer" "${PGBOUNCER_HOST}" "${PGBOUNCER_PORT}" PGBOUNCER_AVAILABLE=$? echo "" @@ -159,9 +152,9 @@ fi # Determine which targets to test TARGETS=() -[ $DIRECT_AVAILABLE -eq 0 ] && TARGETS+=("direct:${DB_PORT}") -[ $PGPOOL_AVAILABLE -eq 0 ] && TARGETS+=("pgpool:${PGPOOL_PORT}") -[ $PGBOUNCER_AVAILABLE -eq 0 ] && TARGETS+=("pgbouncer:${PGBOUNCER_PORT}") +[ $DIRECT_AVAILABLE -eq 0 ] && TARGETS+=("direct:${DB_HOST}:${DB_PORT}") +[ $PGPOOL_AVAILABLE -eq 0 ] && TARGETS+=("pgpool:${PGPOOL_HOST}:${PGPOOL_PORT}") +[ $PGBOUNCER_AVAILABLE -eq 0 ] && TARGETS+=("pgbouncer:${PGBOUNCER_HOST}:${PGBOUNCER_PORT}") echo -e "${BLUE}=== Initializing pgbench tables ===${NC}\n" PGPASSWORD="${DB_PASSWORD}" pgbench -h "${DB_HOST}" -p "${DB_PORT}" -U "${DB_USER}" -i -s "${SCALE_FACTOR}" "${DB_NAME}" @@ -176,7 +169,7 @@ COMPLETED_TESTS=0 # Count total tests for target_info in "${TARGETS[@]}"; do for connections in ${CONNECTION_COUNTS}; do - for protocol in simple extended prepared; do + for protocol in "${PROTOCOLS[@]}"; do TOTAL_TESTS=$((TOTAL_TESTS + 1)) done done @@ -187,16 +180,17 @@ echo -e "Total tests to run: ${TOTAL_TESTS}\n" # Run all test combinations for target_info in "${TARGETS[@]}"; do target=$(echo ${target_info} | cut -d: -f1) - port=$(echo ${target_info} | cut -d: -f2) + host=$(echo ${target_info} | cut -d: -f2) + port=$(echo ${target_info} | cut -d: -f3) echo -e "${BLUE}=== Testing: ${target} ===${NC}\n" for connections in ${CONNECTION_COUNTS}; do - for protocol in simple ; do #extended prepared; do + for protocol in "${PROTOCOLS[@]}"; do COMPLETED_TESTS=$((COMPLETED_TESTS + 1)) echo -e "${BLUE}[${COMPLETED_TESTS}/${TOTAL_TESTS}]${NC}" - run_pgbench "${target}" "${port}" "${connections}" "${protocol}" + run_pgbench "${target}" "${host}" "${port}" "${connections}" "${protocol}" # Brief pause between tests sleep 2 From 3540146b622760d653f4f968f75a841bdbca219f Mon Sep 17 00:00:00 2001 From: xiaolei Date: Fri, 14 Nov 2025 15:55:37 -0500 Subject: [PATCH 12/17] fix unnamed prep statement --- benchmark/scripts/run_benchmark.sh | 3 +-- pool/client.go | 14 +++++++++++--- pool/pool.go | 1 + pool/server.go | 4 ++-- 4 files changed, 15 insertions(+), 7 deletions(-) diff --git a/benchmark/scripts/run_benchmark.sh b/benchmark/scripts/run_benchmark.sh index b07a2f6..5e93512 100755 --- a/benchmark/scripts/run_benchmark.sh +++ b/benchmark/scripts/run_benchmark.sh @@ -3,8 +3,6 @@ # PostgreSQL Connection Pool Benchmark Runner # Compares pgpool vs pgbouncer vs direct connection using pgbench -set -e - # Colors RED='\033[0;31m' GREEN='\033[0;32m' @@ -95,6 +93,7 @@ run_pgbench() { pgbench_cmd+=" -j $(( connections > 10 ? 10 : connections ))" pgbench_cmd+=" -T ${DURATION}" pgbench_cmd+=" -M ${protocol}" + # pgbench_cmd+=" -d" # debug # Set workload (default: TPC-B-like) pgbench_cmd+=" -b tpcb-like" diff --git a/pool/client.go b/pool/client.go index 7609736..c2de9fa 100644 --- a/pool/client.go +++ b/pool/client.go @@ -40,12 +40,17 @@ func hashStmt(sql string) string { } type Stmt struct { + Unnamed bool Hash string Sql string ParamOIDs []uint32 } func (s Stmt) Name() string { + if s.Unnamed { + return "" + } + return "stmt_" + s.Hash } @@ -459,11 +464,14 @@ func (p *Pool) doCancel(cancel *proto.CancelReqMsg) { } func (client *ClientConn) doParse(msg *proto.ParseMsg) { - if _, ok := client.PrepStmts[msg.Name]; !ok { + _, ok := client.PrepStmts[msg.Name] + unamed := msg.Name == "" + if unamed || !ok { // name can be empty refering to default prepred stmt := Stmt{ Hash: hashStmt(msg.Query), Sql: msg.Query, ParamOIDs: msg.ParamOIDs, + Unnamed: unamed, } client.PrepStmts[msg.Name] = &stmt @@ -498,7 +506,7 @@ func (client *ClientConn) doBind(msg *proto.BindMsg) { <-client.Wait } - serverStmt, ok := client.Server.PrepStmts[stmt.Hash] + serverStmt, ok := client.Server.PrepStmts[stmt.Name()] if !ok { slog.Error("server template not exist when bind", "client", client.ID()) @@ -514,7 +522,7 @@ func (client *ClientConn) doBind(msg *proto.BindMsg) { func (client *ClientConn) doDescribe(msg *proto.DescribeMsg) { if stmt, ok := client.PrepStmts[msg.Name]; ok { - if _, ok := client.Server.PrepStmts[stmt.Hash]; !ok { + if _, ok := client.Server.PrepStmts[stmt.Name()]; !ok { client.Server.prepareStmt(stmt) <-client.Wait } diff --git a/pool/pool.go b/pool/pool.go index 2efaf8a..69bd105 100644 --- a/pool/pool.go +++ b/pool/pool.go @@ -153,6 +153,7 @@ func (p *Pool) wait(client *ClientConn) { func (p *Pool) use(server *ServConn, client *ClientConn) { server.lock.Lock() server.BindClient(client) + delete(server.PrepStmts, "") // clear up unnamed prepare stmt cache server.State = ServerInUse server.lock.Unlock() } diff --git a/pool/server.go b/pool/server.go index 5f2caab..91bc3de 100644 --- a/pool/server.go +++ b/pool/server.go @@ -280,11 +280,11 @@ func (sc *ServConn) UnbindClient() { } func (sc *ServConn) prepareStmt(stmt *Stmt) bool { - if _, ok := sc.PrepStmts[stmt.Hash]; ok { + if _, ok := sc.PrepStmts[stmt.Name()]; ok && !stmt.Unnamed { return false } - sc.PrepStmts[stmt.Hash] = stmt + sc.PrepStmts[stmt.Name()] = stmt data := proto.ParseMsg{ Name: stmt.Name(), From 2bf9af4268a48b48bedc575c058b74573a50669a Mon Sep 17 00:00:00 2001 From: xiaolei Date: Fri, 14 Nov 2025 15:57:34 -0500 Subject: [PATCH 13/17] lint --- pool/client.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pool/client.go b/pool/client.go index c2de9fa..979497e 100644 --- a/pool/client.go +++ b/pool/client.go @@ -466,7 +466,7 @@ func (p *Pool) doCancel(cancel *proto.CancelReqMsg) { func (client *ClientConn) doParse(msg *proto.ParseMsg) { _, ok := client.PrepStmts[msg.Name] unamed := msg.Name == "" - if unamed || !ok { // name can be empty refering to default prepred + if unamed || !ok { stmt := Stmt{ Hash: hashStmt(msg.Query), Sql: msg.Query, From 84e4bd6f3b5f1ceb266075192ba13f05152096af Mon Sep 17 00:00:00 2001 From: xiaolei Date: Mon, 17 Nov 2025 16:26:02 -0500 Subject: [PATCH 14/17] fix prepared benmark --- benchmark/config/pgpool.conf | 2 +- benchmark/scripts/run_benchmark.sh | 5 +-- pool/client.go | 49 ++++++++++++++++++++---------- pool/pool.go | 6 +++- pool/server.go | 1 + 5 files changed, 43 insertions(+), 20 deletions(-) diff --git a/benchmark/config/pgpool.conf b/benchmark/config/pgpool.conf index 2709f96..40b967e 100644 --- a/benchmark/config/pgpool.conf +++ b/benchmark/config/pgpool.conf @@ -12,4 +12,4 @@ name = pgtest auth_type = scram password = test123 max_conn = 20 -max_clients = 200 +max_clients = 200 \ No newline at end of file diff --git a/benchmark/scripts/run_benchmark.sh b/benchmark/scripts/run_benchmark.sh index 5e93512..88a6eee 100755 --- a/benchmark/scripts/run_benchmark.sh +++ b/benchmark/scripts/run_benchmark.sh @@ -28,7 +28,7 @@ PGBOUNCER_HOST="${PGBOUNCER_HOST:-localhost}" PGBOUNCER_PORT="${PGBOUNCER_PORT:-6432}" # Benchmark configuration -DURATION="${DURATION:-60}" +DURATION="${DURATION:-30}" SCALE_FACTOR="${SCALE_FACTOR:-1}" CONNECTION_COUNTS="${CONNECTION_COUNTS:-10 50}" PROTOCOLS=("simple" "extended" "prepared") @@ -90,7 +90,8 @@ run_pgbench() { pgbench_cmd+=" -p ${port}" pgbench_cmd+=" -U ${DB_USER}" pgbench_cmd+=" -c ${connections}" - pgbench_cmd+=" -j $(( connections > 10 ? 10 : connections ))" + # have to ensure thread match connection, otherwise prepared query will stuck with pooling + pgbench_cmd+=" -j ${connections}" pgbench_cmd+=" -T ${DURATION}" pgbench_cmd+=" -M ${protocol}" # pgbench_cmd+=" -d" # debug diff --git a/pool/client.go b/pool/client.go index 979497e..e79cec7 100644 --- a/pool/client.go +++ b/pool/client.go @@ -69,18 +69,25 @@ type clientAuth struct { scram scramInfo } +const ( + ExtendedQueryParsed = 0x1 + ExtendedQueryBinded = 0x2 + ExtendedQueryExecuted = 0x4 +) + type ClientConn struct { - node Node - msgReader *proto.MessageReader - Conn *net.TCPConn - ErrCount int - ProcID uint32 - Secret uint32 - auth clientAuth - PrepStmts map[string]*Stmt - Server *ServConn - Wait chan WaitType - State ClientState + node Node + msgReader *proto.MessageReader + Conn *net.TCPConn + ErrCount int + ProcID uint32 + Secret uint32 + auth clientAuth + PrepStmts map[string]*Stmt + Server *ServConn + ExtendedState int + Wait chan WaitType + State ClientState } func (client *ClientConn) ID() string { @@ -376,6 +383,7 @@ func (p *Pool) handleClient(client *ClientConn) { if client.Server == nil { p.wait(client) } + client.ExtendedState = 0 client.State = ClientSyncWait client.Server.State = ServerInUse @@ -383,21 +391,32 @@ func (p *Pool) handleClient(client *ClientConn) { if client.Server == nil { p.wait(client) } + m := msg.(*proto.ParseMsg) + client.ExtendedState &= ExtendedQueryParsed client.Server.State = ServerInUse - client.doParse(msg.(*proto.ParseMsg)) + client.doParse(m) continue + case proto.Execute: + client.ExtendedState |= ExtendedQueryExecuted + // BIND can be sent as first message for new extended query case proto.Bind: if client.Server == nil { p.wait(client) } + client.ExtendedState |= ExtendedQueryBinded client.Server.State = ServerInUse client.doBind(msg.(*proto.BindMsg)) continue - // last client message to sync with server ready for query - case proto.Sync, proto.CopyFail, proto.CopyDone: + case proto.Sync: + // only sync wait after execute + if (client.ExtendedState & ExtendedQueryExecuted) > 0 { + client.State = ClientSyncWait + } + + case proto.CopyFail, proto.CopyDone: client.State = ClientSyncWait default: @@ -527,8 +546,6 @@ func (client *ClientConn) doDescribe(msg *proto.DescribeMsg) { <-client.Wait } - slog.Debug("client", "id", client.ID(), "stmt", fmt.Sprintf("%#v", stmt)) - _ = client.Server.Write(&proto.DescribeMsg{ Name: stmt.Name(), ObjectType: 'S', diff --git a/pool/pool.go b/pool/pool.go index 69bd105..77cbe8c 100644 --- a/pool/pool.go +++ b/pool/pool.go @@ -145,15 +145,19 @@ func (p *Pool) do() { } func (p *Pool) wait(client *ClientConn) { + slog.Debug("Wait Start", "client", client.ID()) client.State = ClientWait p.WaitLst.PushBack(client) <-client.Wait + slog.Debug("Wait End", "client", client.ID()) } func (p *Pool) use(server *ServConn, client *ClientConn) { server.lock.Lock() server.BindClient(client) - delete(server.PrepStmts, "") // clear up unnamed prepare stmt cache + // clear up unnamed prepare stmt cache + delete(client.PrepStmts, "") + delete(server.PrepStmts, "") server.State = ServerInUse server.lock.Unlock() } diff --git a/pool/server.go b/pool/server.go index 91bc3de..7b39e40 100644 --- a/pool/server.go +++ b/pool/server.go @@ -85,6 +85,7 @@ func (p *Pool) handleServer(sc *ServConn) { switch m.Type() { case proto.ReadyForQuery: + // TODO: client can be removed asynchronously on error if sc.Client != nil { _ = sc.Client.Write(m) msg := m.(*proto.ReadyQuery) From 36ea0bf46e2904b37a689003191042bdea062a2b Mon Sep 17 00:00:00 2001 From: xiaolei Date: Wed, 19 Nov 2025 11:30:38 -0500 Subject: [PATCH 15/17] clean up --- pool/client.go | 40 ++++++++++++---------------------------- 1 file changed, 12 insertions(+), 28 deletions(-) diff --git a/pool/client.go b/pool/client.go index e79cec7..024f90a 100644 --- a/pool/client.go +++ b/pool/client.go @@ -69,25 +69,18 @@ type clientAuth struct { scram scramInfo } -const ( - ExtendedQueryParsed = 0x1 - ExtendedQueryBinded = 0x2 - ExtendedQueryExecuted = 0x4 -) - type ClientConn struct { - node Node - msgReader *proto.MessageReader - Conn *net.TCPConn - ErrCount int - ProcID uint32 - Secret uint32 - auth clientAuth - PrepStmts map[string]*Stmt - Server *ServConn - ExtendedState int - Wait chan WaitType - State ClientState + node Node + msgReader *proto.MessageReader + Conn *net.TCPConn + ErrCount int + ProcID uint32 + Secret uint32 + auth clientAuth + PrepStmts map[string]*Stmt + Server *ServConn + Wait chan WaitType + State ClientState } func (client *ClientConn) ID() string { @@ -383,7 +376,6 @@ func (p *Pool) handleClient(client *ClientConn) { if client.Server == nil { p.wait(client) } - client.ExtendedState = 0 client.State = ClientSyncWait client.Server.State = ServerInUse @@ -392,29 +384,21 @@ func (p *Pool) handleClient(client *ClientConn) { p.wait(client) } m := msg.(*proto.ParseMsg) - client.ExtendedState &= ExtendedQueryParsed client.Server.State = ServerInUse client.doParse(m) continue - case proto.Execute: - client.ExtendedState |= ExtendedQueryExecuted - // BIND can be sent as first message for new extended query case proto.Bind: if client.Server == nil { p.wait(client) } - client.ExtendedState |= ExtendedQueryBinded client.Server.State = ServerInUse client.doBind(msg.(*proto.BindMsg)) continue case proto.Sync: - // only sync wait after execute - if (client.ExtendedState & ExtendedQueryExecuted) > 0 { - client.State = ClientSyncWait - } + client.State = ClientSyncWait case proto.CopyFail, proto.CopyDone: client.State = ClientSyncWait From baf4e4cbf0720353e853512a98fd22f0285afdd0 Mon Sep 17 00:00:00 2001 From: xiaolei Date: Wed, 19 Nov 2025 16:51:58 -0500 Subject: [PATCH 16/17] optimize --- benchmark/scripts/run_benchmark.sh | 2 +- pool/client.go | 10 ++++------ 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/benchmark/scripts/run_benchmark.sh b/benchmark/scripts/run_benchmark.sh index 88a6eee..79f4c1d 100755 --- a/benchmark/scripts/run_benchmark.sh +++ b/benchmark/scripts/run_benchmark.sh @@ -30,7 +30,7 @@ PGBOUNCER_PORT="${PGBOUNCER_PORT:-6432}" # Benchmark configuration DURATION="${DURATION:-30}" SCALE_FACTOR="${SCALE_FACTOR:-1}" -CONNECTION_COUNTS="${CONNECTION_COUNTS:-10 50}" +CONNECTION_COUNTS="${CONNECTION_COUNTS:-10 30 50}" PROTOCOLS=("simple" "extended" "prepared") # Results directory diff --git a/pool/client.go b/pool/client.go index 024f90a..9478144 100644 --- a/pool/client.go +++ b/pool/client.go @@ -396,12 +396,10 @@ func (p *Pool) handleClient(client *ClientConn) { client.Server.State = ServerInUse client.doBind(msg.(*proto.BindMsg)) continue - - case proto.Sync: - client.State = ClientSyncWait - - case proto.CopyFail, proto.CopyDone: - client.State = ClientSyncWait + case proto.Sync, proto.CopyFail, proto.CopyDone: + if p.WaitLst.Len() > 0 { + client.State = ClientSyncWait + } default: } From fec07d2398abbd8efe3d1d1677dff488cafd2c7a Mon Sep 17 00:00:00 2001 From: xiaolei Date: Fri, 21 Nov 2025 10:14:12 -0500 Subject: [PATCH 17/17] wrap up --- LICENSE | 682 +------------------ README.md | 80 +-- benchmark/README.md | 141 +--- benchmark/config/{pgpool.conf => pgpool.ini} | 0 benchmark/report.md | 106 +++ benchmark/scripts/run_benchmark.sh | 2 +- benchmark/scripts/setup.sh | 4 +- main.go | 27 +- 8 files changed, 189 insertions(+), 853 deletions(-) rename benchmark/config/{pgpool.conf => pgpool.ini} (100%) create mode 100644 benchmark/report.md diff --git a/LICENSE b/LICENSE index be3f7b2..ff76454 100644 --- a/LICENSE +++ b/LICENSE @@ -1,661 +1,21 @@ - GNU AFFERO GENERAL PUBLIC LICENSE - Version 3, 19 November 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU Affero General Public License is a free, copyleft license for -software and other kinds of works, specifically designed to ensure -cooperation with the community in the case of network server software. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -our General Public Licenses are intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - Developers that use our General Public Licenses protect your rights -with two steps: (1) assert copyright on the software, and (2) offer -you this License which gives you legal permission to copy, distribute -and/or modify the software. - - A secondary benefit of defending all users' freedom is that -improvements made in alternate versions of the program, if they -receive widespread use, become available for other developers to -incorporate. Many developers of free software are heartened and -encouraged by the resulting cooperation. However, in the case of -software used on network servers, this result may fail to come about. -The GNU General Public License permits making a modified version and -letting the public access it on a server without ever releasing its -source code to the public. - - The GNU Affero General Public License is designed specifically to -ensure that, in such cases, the modified source code becomes available -to the community. It requires the operator of a network server to -provide the source code of the modified version running there to the -users of that server. Therefore, public use of a modified version, on -a publicly accessible server, gives the public access to the source -code of the modified version. - - An older license, called the Affero General Public License and -published by Affero, was designed to accomplish similar goals. This is -a different license, not a version of the Affero GPL, but Affero has -released a new version of the Affero GPL which permits relicensing under -this license. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU Affero General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Remote Network Interaction; Use with the GNU General Public License. - - Notwithstanding any other provision of this License, if you modify the -Program, your modified version must prominently offer all users -interacting with it remotely through a computer network (if your version -supports such interaction) an opportunity to receive the Corresponding -Source of your version by providing access to the Corresponding Source -from a network server at no charge, through some standard or customary -means of facilitating copying of software. This Corresponding Source -shall include the Corresponding Source for any work covered by version 3 -of the GNU General Public License that is incorporated pursuant to the -following paragraph. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the work with which it is combined will remain governed by version -3 of the GNU General Public License. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU Affero General Public License from time to time. Such new versions -will be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU Affero General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU Affero General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU Affero General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If your software can interact with users remotely through a computer -network, you should also make sure that it provides a way for users to -get its source. For example, if your program is a web application, its -interface could display a "Source" link that leads users to an archive -of the code. There are many ways you could offer source, and different -solutions will be better for different programs; see section 13 for the -specific requirements. - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU AGPL, see -. +MIT License + +Copyright (c) 2025 pgpool contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index 9b697ad..b6efb73 100644 --- a/README.md +++ b/README.md @@ -15,16 +15,15 @@ A PostgreSQL connection pooler written in Go that acts as a proxy between client - Trust (no password) - **PostgreSQL Wire Protocol**: Full implementation supporting 40+ message types - **Extended Query Support**: Parse, Bind, Execute, and Sync operations -- **Prepared Statement Caching**: SHA256-based deduplication across connections +- **Prepared Statement Caching**: Triggers prepare implicitly if server connection misses preprared on new pairing - **Copy Command Support**: COPY FROM/COPY TO operations -- **Concurrent Connection Handling**: Thread-safe with async client-server pairing ## Quick Start ### Prerequisites -- Go 1.22.6 or later -- PostgreSQL server (tested with PostgreSQL 15) +- Go 1.25 or later +- PostgreSQL server (tested with PostgreSQL 16) ### Installation @@ -59,16 +58,27 @@ max_clients = 100 ### Running ```bash -# Run with default config (pgpool.conf) +# Run with default config (config.ini) ./pgpool # Run with custom config -./pgpool -conf /path/to/config.conf - -# Run with debug logging -./pgpool -debug +./pgpool --config /path/to/config.ini +# or shorthand +./pgpool -c /path/to/config.ini ``` +### Command-Line Flags + +| Flag | Shorthand | Default | Description | +|------|-----------|---------|-------------| +| `--config` | `-c` | `./config.ini` | Path to configuration file | +| `--log-level` | `-l` | `info` | Set log level: debug, info, warn, error | +| `--verbose` | `-v` | `false` | Enable debug logging (equivalent to --log-level debug) | +| `--quiet` | `-q` | `false` | Show errors only (equivalent to --log-level error) | + +**Environment Variables:** +- `PGPOOL_LOG_LEVEL`: Set default log level (overridden by command-line flags) + ## Configuration Reference ### Application Section @@ -115,11 +125,6 @@ pgpool supports multiple authentication methods for securing client connections. - Client → pgpool (validates client connections) - pgpool → PostgreSQL server (authenticates with the database) -**Security benefits:** -- Passwords are never sent in plain text over the network -- Resistant to replay attacks -- More secure than MD5 or clear password authentication -- Default authentication method in PostgreSQL 14+ ### Trust @@ -169,51 +174,20 @@ go build -race -v -o pgpool . GOOS=linux GOARCH=amd64 go build -v -o pgpool-linux . ``` -## Architecture - -### Connection Flow - -1. **Client connects** to pgpool on configured address -2. **Authentication** happens between client and pgpool -3. **Pool assigns** a free server connection or creates a new one -4. **Queries are proxied** between client and server -5. **Connection returns** to pool when client disconnects - -### Thread Safety +### Benchmark -- `sync.RWMutex` for concurrent access to shared data structures -- `sync.Map` for pool storage -- Thread-safe `Deque` and `DList` implementations for connection queues +Check [benchmark](benchmark/README.md) -## Performance Considerations +## TODO -- **Connection Reuse**: Minimizes overhead of establishing PostgreSQL connections -- **Prepared Statement Caching**: Reduces parse overhead using SHA256-based deduplication -- **Async Connection Pairing**: Non-blocking queue-based matching of clients to servers -- **Buffer Management**: Shared 4KB buffers with rewindable offsets for efficient reading - -## CI/CD - -GitHub Actions workflow runs on every push: - -1. Build check with Go 1.25.3 -2. Linting with golangci-lint -3. Unit tests with coverage reporting -4. Integration tests with PostgreSQL 15 -5. Coverage upload to Codecov +* SSL support +* Performance improvement: + granular locking on client/server list + active wait list processing ## License -This project is licensed under the **GNU Affero General Public License v3.0** (AGPL-3.0). - -### What does this mean? - -- **Free and Open Source**: You can freely use, modify, and distribute this software -- **Copyleft**: If you modify and distribute this software, you must release your modifications under the same license -- **Network Use**: If you run a modified version of this software on a server and let others interact with it over a network, you must make your modified source code available to those users -- **Strong Protection**: Ensures that all users, including those who interact with the software over a network, have access to the source code - -This license is particularly important for network services like pgpool, as it ensures that improvements and modifications made to the software remain available to the community, even when deployed as a service. +This project is licensed under the **MIT License**. See the [LICENSE](LICENSE) file for full details. diff --git a/benchmark/README.md b/benchmark/README.md index 1d30cad..9f85838 100644 --- a/benchmark/README.md +++ b/benchmark/README.md @@ -6,7 +6,6 @@ Comprehensive benchmarking suite for comparing **pgpool** vs **pgbouncer** vs ** This benchmark suite tests: - **Throughput** (transactions per second) -- **Latency** (average, p50, p95, p99) - **Connection overhead** (initial connection time) - **Protocol performance** (simple, extended, prepared statements) - **Workload patterns** (read-only, read-write, complex queries) @@ -16,7 +15,7 @@ This benchmark suite tests: ``` benchmark/ ├── config/ # Configuration files -│ ├── pgpool.conf # pgpool configuration +│ ├── pgpool.ini # pgpool configuration │ ├── pgbouncer.ini # pgbouncer configuration │ └── userlist.txt # pgbouncer auth file ├── scripts/ # Benchmark scripts @@ -27,6 +26,7 @@ benchmark/ ├── results/ # Benchmark results (auto-generated) │ └── YYYYMMDD_HHMMSS/ # Timestamped results └── README.md # This file +└── report.md # sample report ``` ## Prerequisites @@ -68,7 +68,7 @@ This will: #### pgpool Configuration -Edit `config/pgpool.conf`: +Edit `config/pgpool.ini`: ```ini [app] addr = localhost:5433 @@ -91,32 +91,20 @@ max_clients = 200 Edit `config/pgbouncer.ini` and `config/userlist.txt` with your credentials. -**Important**: Generate SCRAM hash for pgbouncer: -```bash -# Connect to PostgreSQL -psql -U postgres -d postgres -# Get the password hash -SELECT rolpassword FROM pg_authid WHERE rolname = 'pgtest'; -``` - -Copy the hash to `config/userlist.txt`: -``` -"pgtest" "SCRAM-SHA-256$4096:..." -``` - ### 3. Start Poolers #### Start pgpool ```bash # In terminal 1 cd /path/to/pgpool -./pgpool -conf benchmark/config/pgpool.conf -debug +./pgpool -conf benchmark/config/pgpool.ini -debug ``` #### Start pgbouncer (optional) ```bash # In terminal 2 -pgbouncer -d benchmark/config/pgbouncer.ini +cd benchmark/config +pgbouncer -d pgbouncer.ini ``` ### 4. Run Benchmarks @@ -125,12 +113,6 @@ pgbouncer -d benchmark/config/pgbouncer.ini ./scripts/run_benchmark.sh ``` -Default settings: -- Duration: 60 seconds per test -- Connections: 10, 50, 100 -- Workload: pgbench default TPC-B-like workload -- Protocols: simple, extended, prepared - ### 5. Generate Report ```bash @@ -165,18 +147,6 @@ export SCALE_FACTOR=10 # pgbench scale factor export CONNECTION_COUNTS="10 50 100 200" # connection counts to test ``` -### Custom Benchmark Run - -```bash -# Quick test (30s, fewer connections) -DURATION=30 CONNECTION_COUNTS="10 50" ./scripts/run_benchmark.sh - -# Heavy load test (120s, many connections) -DURATION=120 CONNECTION_COUNTS="50 100 200 500" ./scripts/run_benchmark.sh - -# Test with larger scale factor (more data) -SCALE_FACTOR=100 ./scripts/run_benchmark.sh -``` ## Workload Description @@ -212,27 +182,7 @@ The TPC-B workload is automatically initialized by pgbench with the specified sc ### Sample Report Output -```markdown -## Workload: tpcb - -### Protocol: extended - -#### Throughput (TPS - Higher is Better) - -| Connections | direct | pgpool | pgbouncer | -|-------------|--------|--------|-----------| -| 10 | 15234 | 14876 | 15102 | -| 50 | 42341 | 41203 | 42012 | -| 100 | 52431 | 51234 | 51876 | - -#### Average Latency (ms - Lower is Better) - -| Connections | direct | pgpool | pgbouncer | -|-------------|--------|--------|-----------| -| 10 | 0.65 | 0.67 | 0.66 | -| 50 | 1.18 | 1.21 | 1.19 | -| 100 | 1.91 | 1.95 | 1.93 | -``` +see [report](report.md) ## Cleanup @@ -257,80 +207,3 @@ Test behavior under extreme load: ```bash CONNECTION_COUNTS="100 200 500 1000" DURATION=120 ./scripts/run_benchmark.sh ``` - -#### Protocol Comparison -The benchmark automatically tests all three protocol modes: -- **simple**: Simple query protocol -- **extended**: Extended query protocol with unnamed statements -- **prepared**: Named prepared statements - -### Resource Monitoring - -Monitor system resources during benchmark: - -```bash -# CPU and memory usage -watch -n 1 'ps aux | grep -E "(pgpool|pgbouncer|postgres)"' - -# Connection counts -watch -n 1 'ss -tn | grep -E "(5432|5433|6432)" | wc -l' - -# Database activity -watch -n 1 'psql -U pgtest -c "SELECT count(*), state FROM pg_stat_activity GROUP BY state;"' -``` - -### Analyzing CSV Data - -The `results.csv` file can be imported into spreadsheet tools or analyzed with scripts: - -```bash -# Find best TPS for each target -awk -F, 'NR>1 {print $1,$5}' results.csv | sort -k2 -rn | head -3 - -# Average latency by target -awk -F, 'NR>1 {sum[$1]+=$6; count[$1]++} END {for(t in sum) print t, sum[t]/count[t]}' results.csv -``` - -## Troubleshooting - -### pgpool won't start -- Check if port 5433 is already in use: `lsof -i :5433` -- Verify config file path is correct -- Check PostgreSQL is accessible on port 5432 - -### pgbouncer authentication fails -- Ensure userlist.txt has correct SCRAM hash -- Check pgbouncer.ini has `auth_type = scram-sha-256` -- Verify PostgreSQL user exists and has correct password - -### pgbench fails with connection error -- Verify poolers are running: `ps aux | grep -E "(pgpool|pgbouncer)"` -- Test direct PostgreSQL connection first -- Check firewall settings - -### Low TPS numbers -- Ensure PostgreSQL is properly tuned -- Check system resources (CPU, memory, disk I/O) -- Verify network latency is minimal (use localhost) -- Increase shared_buffers and max_connections in postgresql.conf - -## Best Practices - -1. **Run benchmarks on dedicated hardware** to avoid interference -2. **Warm up** the database before benchmarking (run a quick test first) -3. **Run multiple iterations** and average results -4. **Monitor system resources** during tests -5. **Use consistent configuration** across all poolers -6. **Test realistic workloads** that match your production patterns -7. **Consider both average and tail latencies** (P95, P99) - -## Contributing - -The benchmark suite uses pgbench's default TPC-B-like workload. If you need to test custom workloads, you can: -1. Create SQL files with pgbench-compatible syntax -2. Modify `run_benchmark.sh` to reference your custom workload files -3. Use pgbench variable syntax (e.g., `\set id random(1, 1000)`) - -## License - -This benchmark suite is part of the pgpool project and licensed under AGPL-3.0. diff --git a/benchmark/config/pgpool.conf b/benchmark/config/pgpool.ini similarity index 100% rename from benchmark/config/pgpool.conf rename to benchmark/config/pgpool.ini diff --git a/benchmark/report.md b/benchmark/report.md new file mode 100644 index 0000000..957db1c --- /dev/null +++ b/benchmark/report.md @@ -0,0 +1,106 @@ +# PostgreSQL Connection Pool Benchmark Report + +## System Info +``` +Operating System + - Distribution: Ubuntu 24.04.2 LTS (Noble Numbat) + - Kernel: Linux 6.14.0-33-generic + - Architecture: x86_64 (64-bit) + +CPU + - Model: Intel(R) Core(TM) i7-3615QM @ 2.30GHz + - Cores: 4 physical cores, 8 threads (hyperthreading enabled) + - Cache: L1d: 128 KiB, L1i: 128 KiB, L2: 1 MiB, L3: 6 MiB + - Virtualization: VT-x supported + +Memory + - Total RAM: 7.7 GiB + - Used: 3.6 GiB + - Free: 212 MiB + - Buffer/Cache: 4.4 GiB + - Available: 4.1 GiB +``` + +## Configuration +``` +Benchmark Configuration +======================= +Timestamp: 20251119_123527 +Duration: 30s +Scale Factor: 1 +Connection Counts: 10 30 50 +Workload: TPC-B-like (pgbench default) + +Database Configuration +====================== +DB Host: localhost +DB Port: 5432 +DB Name: postgres +DB User: pgtest + +Pool Configuration +========== +pgpool: localhost 5433 +pgbouncer: localhost 6432 +``` + +## Workload: tpcb + +### Protocol: extended + +#### Throughput (TPS - Higher is Better) + +| Connections | direct | pgpool | pgbouncer | +|-------------|-----------|-----------|-----------| +| 10 | 585.238364 | 586.118595 | 604.660117 | +| 30 | 582.777928 | 532.676985 | 714.917133 | +| 50 | 589.293650 | 398.812499 | 783.499747 | + +#### Average Latency (ms - Lower is Better) + +| Connections | direct | pgpool | pgbouncer | +|-------------|-----------|-----------|-----------| +| 10 | 17.087 | 17.061 | 16.538 | +| 30 | 51.478 | 56.319 | 41.963 | +| 50 | 84.847 | 125.372 | 63.816 | + + +### Protocol: prepared + +#### Throughput (TPS - Higher is Better) + +| Connections | direct | pgpool | pgbouncer | +|-------------|-----------|-----------|-----------| +| 10 | 657.164027 | 693.167688 | 700.220246 | +| 30 | 638.176354 | 616.605597 | 818.683994 | +| 50 | 648.179381 | 590.052991 | 841.249706 | + +#### Average Latency (ms - Lower is Better) + +| Connections | direct | pgpool | pgbouncer | +|-------------|-----------|-----------|-----------| +| 10 | 15.217 | 14.427 | 14.281 | +| 30 | 47.009 | 48.653 | 36.644 | +| 50 | 77.139 | 84.738 | 59.435 | + +--- + +### Protocol: simple + +#### Throughput (TPS - Higher is Better) + +| Connections | direct | pgpool | pgbouncer | +|-------------|-----------|-----------|-----------| +| 10 | 619.224861 | 753.693232 | 663.680040 | +| 30 | 608.975762 | 828.391829 | 746.985918 | +| 50 | 613.787577 | 802.184268 | 749.947154 | + +#### Average Latency (ms - Lower is Better) + +| Connections | direct | pgpool | pgbouncer | +|-------------|-----------|-----------|-----------| +| 10 | 16.149 | 13.268 | 15.068 | +| 30 | 49.263 | 36.215 | 40.161 | +| 50 | 81.461 | 62.330 | 66.671 | + +--- diff --git a/benchmark/scripts/run_benchmark.sh b/benchmark/scripts/run_benchmark.sh index 79f4c1d..efee8e7 100755 --- a/benchmark/scripts/run_benchmark.sh +++ b/benchmark/scripts/run_benchmark.sh @@ -30,7 +30,7 @@ PGBOUNCER_PORT="${PGBOUNCER_PORT:-6432}" # Benchmark configuration DURATION="${DURATION:-30}" SCALE_FACTOR="${SCALE_FACTOR:-1}" -CONNECTION_COUNTS="${CONNECTION_COUNTS:-10 30 50}" +CONNECTION_COUNTS="${CONNECTION_COUNTS:-10 50 100}" PROTOCOLS=("simple" "extended" "prepared") # Results directory diff --git a/benchmark/scripts/setup.sh b/benchmark/scripts/setup.sh index 61e27b0..dc1aae9 100755 --- a/benchmark/scripts/setup.sh +++ b/benchmark/scripts/setup.sh @@ -91,10 +91,10 @@ fi echo -e "\n${GREEN}=== Setup Complete ===${NC}\n" echo -e "Configuration files:" -echo -e " pgpool: ${BENCHMARK_DIR}/config/pgpool.conf" +echo -e " pgpool: ${BENCHMARK_DIR}/config/pgpool.ini" echo -e " pgbouncer: ${BENCHMARK_DIR}/config/pgbouncer.ini" echo -e "\nTo start the poolers:" -echo -e " pgpool: ${PGPOOL_BIN} -conf ${BENCHMARK_DIR}/config/pgpool.conf" +echo -e " pgpool: ${PGPOOL_BIN} -conf ${BENCHMARK_DIR}/config/pgpool.ini" echo -e " pgbouncer: pgbouncer -d ${BENCHMARK_DIR}/config/pgbouncer.ini" echo -e "\nTo run benchmarks:" echo -e " ${SCRIPT_DIR}/run_benchmark.sh" diff --git a/main.go b/main.go index ba54352..116ef48 100644 --- a/main.go +++ b/main.go @@ -31,10 +31,33 @@ func parseLogLevel(level string) (slog.Level, error) { func main() { var logLevel string var cfgSrc string - flag.StringVar(&logLevel, "l", "info", "log level (debug, info, warn, error)") - flag.StringVar(&cfgSrc, "c", "./config.ini", "config file") + var verbose bool + var quiet bool + + // Get default log level from environment variable + defaultLogLevel := os.Getenv("PGPOOL_LOG_LEVEL") + if defaultLogLevel == "" { + defaultLogLevel = "info" + } + + // Define flags with both long and short forms + flag.StringVar(&logLevel, "log-level", defaultLogLevel, "set log level (debug, info, warn, error)") + flag.StringVar(&logLevel, "l", defaultLogLevel, "set log level (shorthand for --log-level)") + flag.BoolVar(&verbose, "verbose", false, "enable debug logging") + flag.BoolVar(&verbose, "v", false, "enable debug logging (shorthand)") + flag.BoolVar(&quiet, "quiet", false, "show errors only") + flag.BoolVar(&quiet, "q", false, "show errors only (shorthand)") + flag.StringVar(&cfgSrc, "config", "./config.ini", "config file path") + flag.StringVar(&cfgSrc, "c", "./config.ini", "config file path (shorthand for --config)") flag.Parse() + // Override log level if verbose or quiet flags are set + if verbose { + logLevel = "debug" + } else if quiet { + logLevel = "error" + } + // Set log level level, err := parseLogLevel(logLevel) if err != nil {