-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
225 lines (197 loc) · 5.54 KB
/
main.go
File metadata and controls
225 lines (197 loc) · 5.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
package main
import (
"context"
"errors"
"fmt"
"log/slog"
"os"
"os/signal"
"path/filepath"
"syscall"
"time"
_ "github.com/jackc/pgx/v5/stdlib"
"github.com/spf13/cobra"
"github.com/pg-tools/pgcompare/internal/pgcompare"
)
var Version = "dev"
var (
flagConfig string
flagOut string
flagVerbose bool
)
func main() {
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer cancel()
if err := rootCmd.ExecuteContext(ctx); err != nil {
if errors.Is(err, context.Canceled) {
os.Exit(130)
}
os.Exit(1)
}
}
var rootCmd = &cobra.Command{
Use: "pgcompare",
Short: "PostgreSQL query performance comparison tool",
Version: Version,
}
var runCmd = &cobra.Command{
Use: "run",
Short: "Run benchmark and generate HTML report",
RunE: runBenchmark,
}
func init() {
runCmd.Flags().StringVar(&flagConfig, "config", "", "path to pgcompare.yaml (required)")
runCmd.Flags().StringVar(&flagOut, "out", "", "output path for report.html (default: next to config)")
runCmd.Flags().BoolVarP(&flagVerbose, "verbose", "v", false, "verbose output")
_ = runCmd.MarkFlagRequired("config")
rootCmd.AddCommand(runCmd)
}
func runBenchmark(cmd *cobra.Command, _ []string) error {
logLevel := slog.LevelWarn
if flagVerbose {
logLevel = slog.LevelInfo
}
log := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: logLevel}))
cfg, err := pgcompare.LoadConfig(flagConfig)
if err != nil {
return fmt.Errorf("load config: %w", err)
}
outPath := flagOut
if outPath == "" {
outPath = filepath.Join(cfg.ProjectDir, "report.html")
}
// Parse queries
bench, err := pgcompare.NewBenchmark(log, cfg.DSN)
if err != nil {
return fmt.Errorf("create benchmark: %w", err)
}
defer bench.Close()
beforeQueries, err := bench.ParseQueries(filepath.Join(cfg.ProjectDir, cfg.Benchmark.BeforeQueries))
if err != nil {
return fmt.Errorf("parse before queries: %w", err)
}
afterQueries, err := bench.ParseQueries(filepath.Join(cfg.ProjectDir, cfg.Benchmark.AfterQueries))
if err != nil {
return fmt.Errorf("parse after queries: %w", err)
}
if err := bench.ValidateMatchingQueryNames(beforeQueries, afterQueries); err != nil {
return err
}
// Setup docker
docker, err := pgcompare.NewDockerComparator(log, cfg)
if err != nil {
return fmt.Errorf("create docker comparator: %w", err)
}
ctx := cmd.Context()
defer func() {
cleanupCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := docker.Cleanup(cleanupCtx); err != nil {
log.Error("final cleanup failed", "err", err)
}
}()
startAll := time.Now()
printHeader("pgcompare")
benchLabel := fmt.Sprintf("(%d repeat × %d iter × %d worker)",
cfg.Benchmark.Repeats, cfg.Benchmark.Iterations, cfg.Benchmark.Concurrency)
// Phase: before
p := startPhase("Preparing 'before' environment")
if err := docker.PrepareVersion(ctx, cfg.Migration.BeforeVersion); err != nil {
p.Fail(err)
return fmt.Errorf("prepare before: %w", err)
}
if err := bench.ReadinessCheck(ctx, beforeQueries); err != nil {
p.Fail(err)
return fmt.Errorf("before readiness: %w", err)
}
p.Done()
p = startPhase("Benchmarking 'before' " + benchLabel)
beforeStats, err := bench.RunRepeats(
ctx,
beforeQueries,
uint(cfg.Benchmark.Repeats),
uint(cfg.Benchmark.Iterations),
uint(cfg.Benchmark.Concurrency),
uint(cfg.Benchmark.WarmupIterations),
)
if err != nil {
p.Fail(err)
return fmt.Errorf("bench before: %w", err)
}
beforePlans, err := bench.Explain(ctx, beforeQueries)
if err != nil {
p.Fail(err)
return fmt.Errorf("explain before: %w", err)
}
p.Done()
// Phase: after
p = startPhase("Preparing 'after' environment")
if err := docker.PrepareVersion(ctx, cfg.Migration.AfterVersion); err != nil {
p.Fail(err)
return fmt.Errorf("prepare after: %w", err)
}
if err := bench.ReadinessCheck(ctx, afterQueries); err != nil {
p.Fail(err)
return fmt.Errorf("after readiness: %w", err)
}
p.Done()
p = startPhase("Benchmarking 'after' " + benchLabel)
afterStats, err := bench.RunRepeats(
ctx,
afterQueries,
uint(cfg.Benchmark.Repeats),
uint(cfg.Benchmark.Iterations),
uint(cfg.Benchmark.Concurrency),
uint(cfg.Benchmark.WarmupIterations),
)
if err != nil {
p.Fail(err)
return fmt.Errorf("bench after: %w", err)
}
afterPlans, err := bench.Explain(ctx, afterQueries)
if err != nil {
p.Fail(err)
return fmt.Errorf("explain after: %w", err)
}
p.Done()
// Analyze
diffs, err := bench.DiffPlans(beforeQueries, beforePlans, afterQueries, afterPlans)
if err != nil {
return fmt.Errorf("diff plans: %w", err)
}
speedups := make([]float64, len(beforeStats))
for i := range beforeStats {
if afterStats[i].P95 > 0 {
speedups[i] = float64(beforeStats[i].P95) / float64(afterStats[i].P95)
}
}
data := pgcompare.ReportData{
GeneratedAt: time.Now(),
Iterations: cfg.Benchmark.Iterations,
WarmupIterations: cfg.Benchmark.WarmupIterations,
Concurrency: cfg.Benchmark.Concurrency,
Repeats: cfg.Benchmark.Repeats,
Speedups: speedups,
Before: &pgcompare.BenchResult{
Phase: "before",
Stats: beforeStats,
Plans: beforePlans,
},
After: &pgcompare.BenchResult{
Phase: "after",
Stats: afterStats,
Plans: afterPlans,
},
Diffs: diffs,
Description: cfg.Report.Description,
}
p = startPhase("Generating report")
if err := pgcompare.Generate(data, outPath); err != nil {
p.Fail(err)
return fmt.Errorf("generate report: %w", err)
}
p.Done()
printSummary(data, outPath, time.Since(startAll))
fmt.Println(outPath)
return nil
}