-
Notifications
You must be signed in to change notification settings - Fork 1
/
codegen.go
357 lines (324 loc) · 8.62 KB
/
codegen.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
/*
* Copyright [2020] Sergey Kudasov
*
* 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 loadgen
import (
"fmt"
. "github.com/dave/jennifer/jen"
"github.com/iancoleman/strcase"
"github.com/spf13/viper"
"gopkg.in/yaml.v2"
"io/ioutil"
"os"
"path"
"regexp"
"strings"
)
var (
attackerLabelRe = regexp.MustCompile("(.*) = (.*)")
runConfigsDir = "run_configs"
myLibPackageName = "loadgen"
myLibPackageImportPath = "github.com/insolar/loadgenerator"
repoPrefix = "github.com/insolar"
viperImportPath = "github.com/spf13/viper"
)
type LabelKV struct {
Label string
LabelName string
}
type AttackerWithLabel struct {
Name string
Label string
}
func NewLabelName(label string) string {
return strcase.ToCamel(label + "Label")
}
func NewAttackerStructName(label string) string {
return strcase.ToCamel(label + "Attack")
}
func NewCheckFuncName(label string) string {
return strcase.ToCamel(label + "Check")
}
// CollectLabels read all labels in labels.go
func CollectLabels(path string) []LabelKV {
f := createFileOrAppend(fmt.Sprintf(labelsPath, path))
defer f.Close()
data, err := ioutil.ReadAll(f)
if err != nil {
log.Fatal(err)
}
res := attackerLabelRe.FindAllString(string(data), -1)
labels := make([]LabelKV, 0)
for _, s := range res {
l := strings.Split(s, "=")
labels = append(
labels,
LabelKV{
strings.Trim(l[1], " \""),
strings.Trim(l[0], " \""),
},
)
}
return labels
}
// CodegenAttackersFile generates attacker factory code for every label it found in labels.go, struct will be camelcased with Attack suffix:
//
//package load
//
//import (
// "github.com/insolar/loadgenerator"
// "log"
//)
//
//func AttackerFromName(name string) loadgen.Attack {
// switch name {
// case "user_create":
// return loadgen.WithMonitor(new(UserCreateAttack))
///
// ...
//
// default:
// log.Fatalf("unknown attacker type: %s", name)
// return nil
// }
//}
func CodegenAttackersFile(packageName string, labels []LabelKV) {
cases := make([]Code, 0)
for _, l := range labels {
structName := NewAttackerStructName(l.Label)
fmt.Printf("generating label: %s\ngenerating structName: %s\n", l, structName)
cases = append(cases, Case(Lit(l.Label)).Block(
Return(Qual(myLibPackageImportPath, "WithMonitor").Call(Id("new").Call(Id(structName)))),
))
}
cases = append(cases, Default().Block(
Qual("log", "Fatalf").Call(
Lit("unknown attacker type: %s"),
Id("name"),
),
Return(Nil()),
))
f := NewFile(packageName)
imports := map[string]string{
myLibPackageImportPath: myLibPackageName,
"log": "log",
}
f.ImportNames(imports)
f.Func().Id("AttackerFromName").Params(
Id("name").Id("string"),
).Qual(myLibPackageImportPath, "Attack").Block(
Switch(Id("name")).Block(
cases...,
),
)
if err := f.Save(path.Join(packageName, "attackers.go")); err != nil {
log.Fatal(err)
}
}
func CodegenChecksFile(packageName string, labels []LabelKV) {
cases := make([]Code, 0)
for _, l := range labels {
structName := NewCheckFuncName(l.Label)
fmt.Printf("generating label: %s\ngenerating structName: %s\n", l, structName)
cases = append(cases, Case(Lit(l.Label)).Block(
Return(Id(structName)),
))
}
cases = append(cases, Default().Block(
Qual("log", "Fatalf").Call(
Lit("unknown attacker type: %s"),
Id("name"),
),
Return(Nil()),
))
f := NewFile(packageName)
imports := map[string]string{
myLibPackageImportPath: myLibPackageName,
"log": "log",
}
f.ImportNames(imports)
f.Func().Id("CheckFromName").Params(
Id("name").Id("string"),
).Qual(myLibPackageImportPath, "RuntimeCheckFunc").Block(
Switch(Id("name")).Block(
cases...,
),
)
if err := f.Save(path.Join(packageName, "checks.go")); err != nil {
log.Fatal(err)
}
}
// CodegenLabelsFile generate labels file, add new label for created test:
//
//package load
//
//const (
// UserCreateLabel = "user_create"
// ...
//)
func CodegenLabelsFile(packageName string, labels []LabelKV) {
f := NewFile(packageName)
statements := make([]Code, 0)
for _, kv := range labels {
statements = append(statements, Id(kv.LabelName).Op("=").Lit(kv.Label))
}
f.Const().Defs(
statements...,
)
if err := f.Save(path.Join(packageName, "labels.go")); err != nil {
log.Fatal(err)
}
}
// CodegenAttackerFile generates load test code:
//
//package generated_loadtest
//
//import (
// "context"
// "github.com/insolar/loadgenerator"
//)
//
//type GeneratedAttack struct {
// loadgen.WithRunner
//}
//
//func (a *GeneratedAttack) Setup(hc loadgen.RunnerConfig) error {
// return nil
//}
//func (a *GeneratedAttack) Do(ctx context.Context) loadgen.DoResult {
// return loadgen.DoResult{
// Error: nil,
// RequestLabel: GeneratedLabel,
// }
//}
//func (a *GeneratedAttack) Clone(r *loadgen.Runner) loadgen.Attack {
// return &GeneratedAttack{WithRunner: loadgen.WithRunner{R: r}}
//}
func CodegenAttackerFile(packageName string, label string) {
structName := NewAttackerStructName(label)
labelName := NewLabelName(label)
f := NewFile(packageName)
imports := map[string]string{
myLibPackageImportPath: myLibPackageName,
"context": "context",
}
f.ImportNames(imports)
f.Type().Id(structName).Struct(
Qual(myLibPackageImportPath, "WithRunner"),
)
f.Func().Params(
Id("a").Id("*" + structName),
).Id("Setup").Params(
Id("hc").Qual(myLibPackageImportPath, "RunnerConfig"),
).Error().Block(
Return(Nil()),
)
f.Func().Params(
Id("a").Id("*" + structName),
).Id("Do").Params(
Id("ctx").Qual("context", "Context"),
).Id(myLibPackageName).Dot("DoResult").Block(
Return(
Id(myLibPackageName).Dot("DoResult").Values(Dict{
Id("RequestLabel"): Id(labelName),
Id("Error"): Nil(),
},
),
),
)
f.Func().Params(
Id("a").Id("*" + structName),
).Id("Clone").Params(
Id("r").Id("*" + myLibPackageName).Dot("Runner"),
).Id(myLibPackageName).Dot("Attack").Block(
Return(
Id("&" + structName).Values(Dict{
Id("WithRunner"): Id(myLibPackageName).Dot("WithRunner").Values(Dict{
Id("R"): Id("r"),
}),
},
),
),
)
if err := f.Save(path.Join(packageName, label+"_attack.go")); err != nil {
log.Fatal(err)
}
}
// CodegenMainFile generate loadtest entry point:
//
//package main
//
//import (
// "github.com/insolar/loadgenerator"
// "github.com/insolar/example_loadtest"
// "github.com/insolar/example_loadtest/config"
//)
//
//func main() {
// loadgen.Run(example_loadtest.AttackerFromName, example_loadtest.CheckFromName)
//}
func CodegenMainFile(packageName string) {
targetDir := path.Join(packageName, "cmd", "load")
createDirIfNotExists(targetDir)
f := NewFile("main")
rootPackageName := viper.GetString("root_package_name")
loadTestPackageImportPath := path.Join(repoPrefix, rootPackageName, packageName)
imports := map[string]string{
myLibPackageImportPath: myLibPackageName,
loadTestPackageImportPath: packageName,
}
f.ImportNames(imports)
f.Func().Id("main").Params().Block(
Qual(myLibPackageImportPath, "Run").Call(Qual(loadTestPackageImportPath, "AttackerFromName"), Qual(loadTestPackageImportPath, "CheckFromName")),
)
if err := f.Save(path.Join(targetDir, "main.go")); err != nil {
log.Fatal(err)
}
}
// GenerateSingleRunConfig generates simple config to run test for debug
func GenerateSingleRunConfig(testDir string, label string) {
runCfgPath := path.Join(testDir, runConfigsDir)
createDirIfNotExists(runCfgPath)
suiteCfg := &SuiteConfig{
DumpTransport: true,
HttpTimeout: 20,
Steps: []Step{
{
Name: "load",
ExecutionMode: "sequence",
Handles: []RunnerConfig{
{
HandleName: label,
RampUpStrategy: "exp2",
RPS: 1,
RampUpTimeSec: 1,
AttackTimeSec: 30,
MaxAttackers: 1,
DoTimeoutSec: 40,
Verbose: true,
RecycleData: true,
},
},
},
},
}
cfg, err := yaml.Marshal(suiteCfg)
if err != nil {
log.Fatalf("failed to marshal single run config: %s", err)
}
if err := ioutil.WriteFile(path.Join(runCfgPath, label+".yaml"), cfg, os.ModePerm); err != nil {
log.Fatalf("failed to write single run config for label: %s, %s", label, err)
}
}