-
Notifications
You must be signed in to change notification settings - Fork 32
/
config.go
429 lines (398 loc) · 12.8 KB
/
config.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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
/*
* Copyright (c) 2015-2020 by MemSQL. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package main
import (
"encoding/csv"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"unicode/utf8"
"github.com/awreece/goini"
)
type Config struct {
Flavor DatabaseFlavor
Duration time.Duration
Setup []string
Teardown []string
Jobs map[string]*Job
AcceptedErrors Set
}
func (c *Config) String() string {
return quotedStruct(c)
}
func readQueriesFromReader(df DatabaseFlavor, r io.Reader) ([]string, error) {
queries := make([]string, 0, 1)
if contents, err := ioutil.ReadAll(r); err != nil {
return nil, err
} else {
for _, query := range strings.Split(string(contents), df.QuerySeparator()) {
err := df.CheckQuery(query)
if err != nil && err != EmptyQueryError {
return nil, fmt.Errorf("invalid query %v", err)
} else if err == nil {
queries = append(queries, query)
}
}
}
return queries, nil
}
func readQueriesFromFile(df DatabaseFlavor, queryFile string) ([]string, error) {
file, err := os.Open(queryFile)
if err != nil {
return nil, err
}
return readQueriesFromReader(df, file)
}
type globalSectionParser struct {
config *Config
flavor DatabaseFlavor
}
var globalOptions = goini.DecodeOptionSet{
"duration": &goini.DecodeOption{Kind: goini.UniqueOption,
Usage: "When the test will stop launching new jobs, as a duration " +
" elapsed since setup ",
Parse: func(v string, gsp interface{}) (e error) {
gsp.(*globalSectionParser).config.Duration, e = time.ParseDuration(v)
return e
},
},
"error": &goini.DecodeOption{Kind: goini.MultiOption,
Usage: "Globally accepted errors.",
Parse: func(v string, gspi interface{}) error {
gsp := gspi.(*globalSectionParser)
if gsp.config.AcceptedErrors == nil {
gsp.config.AcceptedErrors = make(Set)
}
gsp.config.AcceptedErrors.Add(v)
return nil
},
},
}
func decodeGlobalSection(df DatabaseFlavor, s goini.RawSection, c *Config) error {
return globalOptions.Decode(s, &globalSectionParser{c, df})
}
type setupSectionParser struct {
queries []string
df DatabaseFlavor
basedir string
}
var setupOptions = goini.DecodeOptionSet{
"query": &goini.DecodeOption{Kind: goini.MultiOption,
Usage: "Setup query to be executed before any jobs are started. " +
"Must be a single query and cannot have any effect on the " +
"connection (e.g USE or BEGIN).",
Parse: func(v string, sspi interface{}) error {
ssp := sspi.(*setupSectionParser)
if e := ssp.df.CheckQuery(v); e != nil {
return e
}
ssp.queries = append(ssp.queries, v)
return nil
},
},
"query-file": &goini.DecodeOption{Kind: goini.MultiOption,
Usage: "Setup query to be executed before any jobs are started. " +
"Must be a single query and cannot have any effect on the " +
"connection (e.g USE or BEGIN).",
Parse: func(v string, sspi interface{}) error {
ssp := sspi.(*setupSectionParser)
if !filepath.IsAbs(v) {
v = filepath.Join(ssp.basedir, v)
}
if qs, err := readQueriesFromFile(ssp.df, v); err != nil {
return err
} else {
ssp.queries = append(ssp.queries, qs...)
return nil
}
},
},
}
func decodeSetupSection(df DatabaseFlavor, s goini.RawSection, basedir string, ss *[]string) error {
parser := setupSectionParser{df: df, basedir: basedir}
err := setupOptions.Decode(s, &parser)
if err == nil {
*ss = parser.queries
}
return err
}
type jobParser struct {
j *Job
df DatabaseFlavor
basedir string
queryArgsFile io.Reader
queryArgsDelim rune
multiQueryAllowed bool
}
var jobOptions = goini.DecodeOptionSet{
"start": &goini.DecodeOption{Kind: goini.UniqueOption,
Usage: "When this job should start, as a duration elapsed since setup.",
Parse: func(v string, jp interface{}) (e error) {
jp.(*jobParser).j.Start, e = time.ParseDuration(v)
return e
},
},
"stop": &goini.DecodeOption{Kind: goini.UniqueOption,
Usage: "When this job should stop, as a duration elapsed since setup.",
Parse: func(v string, jp interface{}) (e error) {
jp.(*jobParser).j.Stop, e = time.ParseDuration(v)
return e
},
},
"query": &goini.DecodeOption{Kind: goini.MultiOption,
Usage: "Query to execute for the job. " +
"Must be a single query and cannot have any effect on the " +
"connection (e.g USE or BEGIN).",
Parse: func(v string, jpi interface{}) error {
jp := jpi.(*jobParser)
if e := jp.df.CheckQuery(v); e != nil {
return e
} else {
jp.j.Queries = append(jp.j.Queries, v)
return nil
}
},
},
"query-file": &goini.DecodeOption{Kind: goini.MultiOption,
Usage: "File containing queries to execute for the job. " +
"Queries are separated by the query-separator and cannot have any " +
"effect on the connection (e.g USE or BEGIN).",
Parse: func(v string, jpi interface{}) error {
jp := jpi.(*jobParser)
if !filepath.IsAbs(v) {
v = filepath.Join(jp.basedir, v)
}
if qs, err := readQueriesFromFile(jp.df, v); err != nil {
return err
} else {
jp.j.Queries = append(jp.j.Queries, qs...)
return nil
}
},
},
"query-args-file": &goini.DecodeOption{Kind: goini.UniqueOption,
Usage: "File containing csv delimited query args, one line per " +
"query.",
Parse: func(v string, jpi interface{}) (err error) {
jp := jpi.(*jobParser)
if !filepath.IsAbs(v) {
v = filepath.Join(jp.basedir, v)
}
jp.queryArgsFile, err = os.Open(v)
return err
},
},
"query-args-delim": &goini.DecodeOption{Kind: goini.UniqueOption,
Usage: "Field separator for csv delimited query args.",
Parse: func(v string, jpi interface{}) error {
jp := jpi.(*jobParser)
if s, err := strconv.Unquote(v); err != nil {
return err
} else if len(s) != 1 {
return errors.New("Must provide exactly one character for delimiter")
} else {
jp.queryArgsDelim, _ = utf8.DecodeRuneInString(s)
return nil
}
},
},
"query-results-file": &goini.DecodeOption{Kind: goini.UniqueOption,
Usage: "Results from executed queries will be written to this file " +
"as comma separated values. If the file already exists, it " +
"will be truncated",
Parse: func(v string, jpi interface{}) (err error) {
jp := jpi.(*jobParser)
if !filepath.IsAbs(v) {
v = filepath.Join(jp.basedir, v)
}
jp.j.QueryResults, err = NewSafeCSVWriter(v)
return err
},
},
"rate": &goini.DecodeOption{Kind: goini.UniqueOption,
Usage: "The number of batches executed per second (default 0.0).",
Parse: func(v string, jpi interface{}) (e error) {
jp := jpi.(*jobParser)
jp.j.Rate, e = strconv.ParseFloat(v, 64)
if e == nil && jp.j.Rate < 0 {
return errors.New("invalid negative value for rate")
}
return e
},
},
"batch-size": &goini.DecodeOption{Kind: goini.UniqueOption,
Usage: "Number of jobs started during one batch (default 1).",
Parse: func(v string, jp interface{}) (e error) {
jp.(*jobParser).j.BatchSize, e = strconv.ParseUint(v, 10, 0)
return e
},
},
"queue-depth": &goini.DecodeOption{Kind: goini.UniqueOption,
Usage: "Number of simultaneous executions of the job allowed.",
Parse: func(v string, jp interface{}) (e error) {
// Is there a way to make go respect numeric prefixes (e.g. 0x0)?
jp.(*jobParser).j.QueueDepth, e = strconv.ParseUint(v, 10, 0)
return e
},
},
"concurrency": &goini.DecodeOption{Kind: goini.UniqueOption,
Usage: "Number of simultaneous executions of the job allowed.",
Parse: func(v string, jp interface{}) (e error) {
// Is there a way to make go respect numeric prefixes (e.g. 0x0)?
jp.(*jobParser).j.QueueDepth, e = strconv.ParseUint(v, 10, 0)
return e
},
},
"count": &goini.DecodeOption{Kind: goini.UniqueOption,
Usage: "Number of time job is executed before stopping.",
Parse: func(v string, jp interface{}) (e error) {
jp.(*jobParser).j.Count, e = strconv.ParseUint(v, 10, 0)
return e
},
},
"multi-query-mode": &goini.DecodeOption{Kind: goini.UniqueOption,
Usage: "Set to 'multi-connection' to signal that the job will execute " +
"multiple queries, but it is safe for them to be on different " +
"connections.",
Parse: func(v string, jp interface{}) error {
if v == "multi-connection" {
jp.(*jobParser).multiQueryAllowed = true
return nil
} else {
return fmt.Errorf("invalid value for multi-query-mode: %s",
strconv.Quote(v))
}
},
},
"query-log-file": &goini.DecodeOption{Kind: goini.UniqueOption,
Usage: "A flat text file containing a log file to replay instead of a " +
"normal job. The query log format is a series of newline " +
"delimited records containing a time in microseconds and a query " +
"separated by a comma. For example, '8644882534,select 1'.",
Parse: func(v string, jpi interface{}) (e error) {
jp := jpi.(*jobParser)
if !filepath.IsAbs(v) {
v = filepath.Join(jp.basedir, v)
}
jp.j.QueryLog, e = os.Open(v)
return e
},
},
}
func decodeJobSection(df DatabaseFlavor, section goini.RawSection, basedir string, job *Job) error {
jp := jobParser{j: job, df: df, basedir: basedir}
if err := jobOptions.Decode(section, &jp); err != nil {
return err
} else if len(job.Queries) == 0 && job.QueryLog == nil {
return errors.New("no query provided")
} else if len(job.Queries) > 0 && job.QueryLog != nil {
return errors.New("cannot have both queries and a query log")
} else if len(job.Queries) > 1 && !jp.multiQueryAllowed {
return fmt.Errorf("must have only one query")
} else if job.Rate == 0 && job.BatchSize > 0 {
return errors.New("can only specify batch-size with rate")
} else if jp.queryArgsDelim != 0 && jp.queryArgsFile == nil {
return errors.New("Cannot set query-args-delim with no query-args-file")
} else if jp.queryArgsFile != nil && job.QueryLog != nil {
return errors.New("Cannot use query-args-file with query-log-file")
}
differentJobTypes := 0
if job.QueueDepth > 0 {
differentJobTypes += 1
}
if job.QueryLog != nil {
differentJobTypes += 1
}
if job.Rate > 0 {
differentJobTypes += 1
}
// The default job type is 1 thread.
if differentJobTypes == 0 {
job.QueueDepth = 1
}
if differentJobTypes > 1 {
return errors.New("Can only specify one of rate, queue-depth, or query-log-file")
}
if job.Rate > 0 && job.BatchSize == 0 {
job.BatchSize = 1
}
if jp.queryArgsFile != nil {
job.QueryArgs = csv.NewReader(jp.queryArgsFile)
if jp.queryArgsDelim != 0 {
job.QueryArgs.Comma = jp.queryArgsDelim
}
}
return nil
}
func decodeConfigJobs(df DatabaseFlavor, iniConfig *goini.RawConfig, basedir string, config *Config) error {
config.Jobs = make(map[string]*Job)
for _, name := range iniConfig.Sections() {
// Don't try to parse a reserved section as a job.
if name == "setup" || name == "teardown" || name == "global" {
continue
}
section := iniConfig.Section(name)
job := new(Job)
job.Name = name
if err := decodeJobSection(df, section, basedir, job); err != nil {
return fmt.Errorf("Error parsing job %s: %v",
strconv.Quote(name), err)
}
config.Jobs[name] = job
}
return nil
}
func parseIniConfig(df DatabaseFlavor, iniConfig *goini.RawConfig, basedir string) (*Config, error) {
var config = new(Config)
config.Flavor = df
if err := decodeGlobalSection(df, iniConfig.GlobalSection, config); err != nil {
return nil, fmt.Errorf("Error parsing global section: %v", err)
}
if err := decodeSetupSection(df, iniConfig.Section("setup"), basedir, &config.Setup); err != nil {
return nil, fmt.Errorf("Error parsing setup section: %v", err)
}
if err := decodeSetupSection(df, iniConfig.Section("teardown"), basedir, &config.Teardown); err != nil {
return nil, fmt.Errorf("Error parsing teardown section: %v", err)
}
if err := decodeConfigJobs(df, iniConfig, basedir, config); err != nil {
return nil, err
}
for name, job := range config.Jobs {
if config.Duration > 0 && job.Start > config.Duration {
return nil, fmt.Errorf("job %s starts after test finishes.",
strconv.Quote(name))
} else if job.Stop > 0 && config.Duration > 0 && job.Stop > config.Duration {
return nil, fmt.Errorf("job %s stops after test finishes.",
strconv.Quote(name))
}
}
return config, nil
}
func parseConfig(df DatabaseFlavor, configFile string, baseDir string) (*Config, error) {
cp := goini.NewRawConfigParser()
cp.ParseFile(configFile)
iniConfig, err := cp.Finish()
if err != nil {
return nil, err
}
return parseIniConfig(df, iniConfig, baseDir)
}