-
Notifications
You must be signed in to change notification settings - Fork 0
/
run.go
237 lines (206 loc) · 5.45 KB
/
run.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
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"math/rand"
"net/http"
"os"
"strings"
"time"
"github.com/INFURA/go-ethlibs/node"
"github.com/jessevdk/go-flags"
ethspam "github.com/p2p-org/ethspam/lib"
vegeta "github.com/tsenart/vegeta/v12/lib"
)
type Options struct {
Target string `long:"target" short:"t" description:"target eth host" required:"false"`
SourceHost string `long:"source" short:"s" description:"source eth host" default:"https://eth.drpc.org"`
Scenario string `long:"scenario" short:"c" description:"scenario file" default:"stages.json"`
Result string `long:"result" short:"r" description:"result file" default:"result.json"`
}
func main() {
options := Options{}
_, err := flags.Parse(&options)
if err != nil {
return
}
fmt.Println("Start")
jsonString, err := os.ReadFile(options.Scenario)
if err != nil {
exit(1, "stages reading error: %v", err)
}
var stages []Stage
err = json.Unmarshal(jsonString, &stages)
if err != nil {
exit(1, "stages parsing error: %v", err)
}
stagesResults := make([]StageResult, 0)
for _, stage := range stages {
fmt.Printf("Stage %v\n", stage.Name)
var stageMetrics vegeta.Metrics
stepResults := make([]StepResult, 0)
target := stage.Target
if target == "" {
target = options.Target
}
for n, step := range stage.Steps {
fmt.Printf("Step %v, rate - %v\n", n+1, step.Rate)
rate := vegeta.Rate{Freq: step.Rate, Per: time.Second}
duration := time.Duration(step.Duration) * time.Second
ctx, cancel := context.WithCancel(context.Background())
targeter := NewEthSpamTargeter(ctx,
target,
stage.Profile,
options.SourceHost,)
attacker := vegeta.NewAttacker()
var metrics vegeta.Metrics
for res := range attacker.Attack(targeter, rate, duration, stage.Name) {
processEthErrors(res)
metrics.Add(res)
stageMetrics.Add(res)
}
attacker.Stop()
metrics.Close()
cancel()
stepResults = append(stepResults, StepResult{StepSummary: metrics})
if metrics.Success < 0.85 {
break
}
fmt.Printf("Step %v - succ: %v - mean: %v - p90: %v \n", n+1, metrics.Success, metrics.Latencies.Mean, metrics.Latencies.P90)
<-time.After(10 * time.Second)
}
stageMetrics.Close()
stageResult := StageResult{
Name: stage.Name,
StageSummary: stageMetrics,
Steps: stepResults,
}
stagesResults = append(stagesResults, stageResult)
fmt.Printf("Stage %v - succ: %v - mean: %v - p90: %v \n", stage.Name, stageMetrics.Success, stageMetrics.Latencies.Mean, stageMetrics.Latencies.P90)
}
fmt.Println("Finish")
res, _ := json.Marshal(stagesResults)
os.WriteFile(options.Result, res, 0644)
}
func processEthErrors(data *vegeta.Result) {
if data.Code != 200 {
return
}
var result RpcResponse
err := json.Unmarshal(data.Body, &result)
if err != nil {
fmt.Printf("Error unmarshalling response JSON: %v\n", err)
data.Code = 500
data.Error = err.Error()
return
}
if result.Error != nil {
if strings.Contains(result.Error.Message, "reverted") || strings.Contains(result.Error.Data, "Reverted") {
// not an error
return
}
data.Code = 500
data.Error = result.Error.Message
}
}
func NewEthSpamTargeter(ctx context.Context, host string, queryParams map[string]int64, parentHost string) vegeta.Targeter {
if host == "" {
exit(1, "host is required")
}
header := http.Header{}
header.Add("Content-Type", "application/json; charset=utf8")
generator, err := ethspam.MakeQueriesGenerator(queryParams)
if err != nil {
exit(1, "failed to install defaults: %s", err)
}
client, err := node.NewClient(ctx, parentHost)
if err != nil {
exit(1, "failed to make a new client: %s", err)
}
mkState := ethspam.StateProducer{
Client: client,
}
stateChannel := make(chan ethspam.State, 1)
go func() {
randSrc := rand.NewSource(time.Now().UnixNano())
state := ethspam.LiveState{
IdGen: ðspam.IdGenerator{},
RandSrc: randSrc,
}
defer close(stateChannel)
for {
newState, err := mkState.Refresh(&state)
if err != nil {
// It can happen in some testnets that most of the blocks
// are empty(no transaction included), don't refresh the
// QueriesGenerator state without new inclusion.
if err == ethspam.ErrEmptyBlock {
select {
case <-time.After(5 * time.Second):
case <-ctx.Done():
return
}
continue
}
fmt.Printf("failed to refresh state: %s", err)
<-time.After(1 * time.Second)
continue
}
select {
case stateChannel <- newState:
case <-ctx.Done():
return
}
select {
case <-time.After(15 * time.Second):
case <-ctx.Done():
return
}
}
}()
state := <-stateChannel
queries := make(chan string)
go func() {
defer close(queries)
for {
// Update state when a new one is emitted
select {
case state = <-stateChannel:
case <-ctx.Done():
return
default:
}
if q, err := generator.Query(state); err == io.EOF {
return
} else if err != nil {
exit(2, "failed to write generated query: %s", err)
} else {
select {
case queries <- q.GetBody():
case <-ctx.Done():
return
}
}
}
}()
return func(tgt *vegeta.Target) error {
if tgt == nil {
return vegeta.ErrNilTarget
}
req, ok := <-queries
if !ok {
return vegeta.ErrNoTargets
}
tgt.URL = host
tgt.Method = "POST"
tgt.Header = header
tgt.Body = []byte(req)
return nil
}
}
func exit(code int, format string, args ...interface{}) {
fmt.Fprintf(os.Stderr, format, args...)
os.Exit(code)
}