/
main.go
241 lines (224 loc) · 6.32 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
// Copyright 2019 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
// smithcmp is a tool to execute random queries on a database. A TOML
// file provides configuration for which databases to connect to. If there
// is more than one, only non-mutating statements are generated, and the
// output is compared, exiting if there is a difference. If there is only
// one database, mutating and non-mutating statements are generated. A
// flag in the TOML controls whether Postgres-compatible output is generated.
//
// Explicit SQL statements can be specified (skipping sqlsmith generation)
// using the top-level SQL array. Placeholders (`$1`, etc.) are
// supported. Random datums of the correct type will be filled in.
package main
import (
"context"
"fmt"
"log"
"math/rand"
"os"
"strings"
"time"
"github.com/BurntSushi/toml"
"github.com/cockroachdb/cockroach/pkg/cmd/cmpconn"
"github.com/cockroachdb/cockroach/pkg/internal/sqlsmith"
"github.com/cockroachdb/cockroach/pkg/sql/randgen"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/lib/pq/oid"
)
func usage() {
const use = `Usage of %s:
%[1]s config.toml
`
fmt.Printf(use, os.Args[0])
os.Exit(1)
}
type options struct {
Postgres bool
InitSQL string
Smither string
Seed int64
TimeoutMins int
StmtTimeoutSecs int
SQL []string
Databases map[string]struct {
Addr string
InitSQL string
AllowMutations bool
}
}
var sqlMutators = []randgen.Mutator{randgen.ColumnFamilyMutator}
func enableMutations(shouldEnable bool, mutations []randgen.Mutator) []randgen.Mutator {
if shouldEnable {
return mutations
}
return nil
}
func main() {
ctx := context.Background()
args := os.Args[1:]
if len(args) != 1 {
usage()
}
tomlData, err := os.ReadFile(args[0])
if err != nil {
log.Fatal(err)
}
var opts options
if err := toml.Unmarshal(tomlData, &opts); err != nil {
log.Fatal(err)
}
timeout := time.Duration(opts.TimeoutMins) * time.Minute
if timeout <= 0 {
timeout = 15 * time.Minute
}
stmtTimeout := time.Duration(opts.StmtTimeoutSecs) * time.Second
if stmtTimeout <= 0 {
stmtTimeout = time.Minute
}
rng := rand.New(rand.NewSource(opts.Seed))
conns := map[string]cmpconn.Conn{}
for name, db := range opts.Databases {
var err error
mutators := enableMutations(opts.Databases[name].AllowMutations, sqlMutators)
if opts.Postgres {
mutators = append(mutators, randgen.PostgresMutator)
}
conns[name], err = cmpconn.NewConnWithMutators(
ctx, db.Addr, rng, mutators, db.InitSQL, opts.InitSQL)
if err != nil {
log.Fatalf("%s (%s): %+v", name, db.Addr, err)
}
}
compare := len(conns) > 1
if opts.Seed < 0 {
opts.Seed = timeutil.Now().UnixNano()
fmt.Println("seed:", opts.Seed)
}
smithOpts := []sqlsmith.SmitherOption{
sqlsmith.AvoidConsts(),
}
if opts.Postgres {
smithOpts = append(smithOpts, sqlsmith.PostgresMode())
} else if compare {
smithOpts = append(smithOpts,
sqlsmith.CompareMode(),
sqlsmith.DisableCRDBFns(),
)
}
if _, ok := conns[opts.Smither]; !ok {
log.Fatalf("Smither option not present in databases: %s", opts.Smither)
}
var smither *sqlsmith.Smither
var stmts []statement
if len(opts.SQL) == 0 {
smither, err = sqlsmith.NewSmither(conns[opts.Smither].DB(), rng, smithOpts...)
if err != nil {
log.Fatal(err)
}
} else {
stmts = make([]statement, len(opts.SQL))
for i, stmt := range opts.SQL {
ps, err := conns[opts.Smither].PGX().Prepare(ctx, "", stmt)
if err != nil {
log.Fatalf("bad SQL statement on %s: %v\nSQL:\n%s", opts.Smither, stmt, err)
}
var placeholders []*types.T
for _, param := range ps.ParamOIDs {
typ, ok := types.OidToType[oid.Oid(param)]
if !ok {
log.Fatalf("unknown oid: %v", param)
}
placeholders = append(placeholders, typ)
}
stmts[i] = statement{
stmt: stmt,
placeholders: placeholders,
}
}
}
var prep, exec string
done := time.After(timeout)
for i, ignoredErrCount := 0, 0; true; i++ {
select {
case <-done:
fmt.Printf("executed query count: %d\nignored error count: %d\n", i, ignoredErrCount)
return
default:
}
fmt.Printf("stmt: %d\n", i)
if smither != nil {
exec = smither.Generate()
} else {
randStatement := stmts[rng.Intn(len(stmts))]
name := fmt.Sprintf("s%d", i)
prep = fmt.Sprintf("PREPARE %s AS\n%s;", name, randStatement.stmt)
var sb strings.Builder
fmt.Fprintf(&sb, "EXECUTE %s", name)
for i, typ := range randStatement.placeholders {
if i > 0 {
sb.WriteString(", ")
} else {
sb.WriteString(" (")
}
d := randgen.RandDatum(rng, typ, true)
fmt.Println(i, typ, d, tree.Serialize(d))
sb.WriteString(tree.Serialize(d))
}
if len(randStatement.placeholders) > 0 {
fmt.Fprintf(&sb, ")")
}
fmt.Fprintf(&sb, ";")
exec = sb.String()
fmt.Println(exec)
}
if compare {
if ignoredErr, err := cmpconn.CompareConns(
ctx, stmtTimeout, conns, prep, exec, true, /* ignoreSQLErrors */
); err != nil {
fmt.Printf("prep:\n%s;\nexec:\n%s;\nERR: %s\n\n", prep, exec, err)
os.Exit(1)
} else if ignoredErr {
ignoredErrCount++
}
} else {
for _, conn := range conns {
if err := conn.Exec(ctx, prep+exec); err != nil {
fmt.Println(err)
}
}
}
// Make sure the servers are alive.
for name, conn := range conns {
start := timeutil.Now()
fmt.Printf("pinging %s...", name)
if err := conn.Ping(ctx); err != nil {
fmt.Printf("\n%s: ping failure: %v\nprevious SQL:\n%s;\n%s;\n", name, err, prep, exec)
// Try to reconnect.
db := opts.Databases[name]
newConn, err := cmpconn.NewConnWithMutators(
ctx, db.Addr, rng, enableMutations(db.AllowMutations, sqlMutators),
db.InitSQL, opts.InitSQL,
)
if err != nil {
log.Fatalf("tried to reconnect: %v\n", err)
}
conns[name] = newConn
}
fmt.Printf(" %s\n", timeutil.Since(start))
}
}
}
type statement struct {
stmt string
placeholders []*types.T
}