-
Notifications
You must be signed in to change notification settings - Fork 4
/
replay.go
216 lines (205 loc) · 5.29 KB
/
replay.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
package main
import (
"bytes"
"context"
"fmt"
"io"
"net/http"
"os"
"slices"
"time"
"github.com/cenkalti/backoff/v4"
"github.com/go-faster/errors"
"github.com/go-faster/yaml"
"github.com/klauspost/compress/snappy"
"github.com/klauspost/compress/zstd"
"github.com/schollz/progressbar/v3"
"github.com/spf13/cobra"
"go.uber.org/atomic"
"golang.org/x/sync/errgroup"
"github.com/go-faster/oteldb/internal/otelbench"
"github.com/go-faster/oteldb/internal/prompb"
)
type Replay struct {
Target string
Source string
Encoding string
ReportPath string
Workers int
points atomic.Uint64
}
func (r *Replay) report(compressedData []byte) error {
if r.ReportPath == "" {
return nil
}
var (
data []byte
err error
)
switch r.Encoding {
case "zstd":
reader, err := zstd.NewReader(bytes.NewReader(compressedData))
if err != nil {
return errors.Wrap(err, "create decoder")
}
defer reader.Close()
if data, err = io.ReadAll(reader); err != nil {
return errors.Wrap(err, "read data")
}
case "snappy":
if data, err = snappy.Decode(data, compressedData); err != nil {
return errors.Wrap(err, "decode data")
}
default:
return errors.Errorf("unsupported encoding %q", r.Encoding)
}
var writeRequest prompb.WriteRequest
if err := writeRequest.Unmarshal(data); err != nil {
return errors.Wrap(err, "unmarshal request")
}
r.points.Add(uint64(len(writeRequest.Timeseries)))
return nil
}
type ReplayReport struct {
Points int `yaml:"points" json:"points"`
DurationNanos int64 `yaml:"duration_nanos" json:"durationNanos"`
PointsPerSecond int `yaml:"points_per_second" json:"pointsPerSecond"`
}
func (r *Replay) Run(ctx context.Context) error {
f, err := os.Open(r.Source)
if err != nil {
return errors.Wrap(err, "open file")
}
defer func() {
if err := f.Close(); err != nil {
fmt.Println(">> close:", err)
}
}()
stat, err := f.Stat()
if err != nil {
return errors.Wrap(err, "stat file")
}
pb := progressbar.DefaultBytes(
stat.Size(),
"sending",
)
pbr := progressbar.NewReader(f, pb)
d := otelbench.NewReader(&pbr)
client := &http.Client{
Timeout: time.Minute,
}
fn := func(data []byte) error {
ctx, cancel := context.WithTimeout(ctx, time.Minute)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodPost, r.Target, bytes.NewReader(data))
if err != nil {
return errors.Wrap(err, "create request")
}
req.Header.Set("Content-Type", "application/x-protobuf")
req.Header.Set("Content-Encoding", r.Encoding)
res, err := client.Do(req)
if err != nil {
return errors.Wrap(err, "do request")
}
defer func() {
_ = res.Body.Close()
}()
out, _ := io.ReadAll(io.LimitReader(res.Body, 512))
if len(out) == 0 {
out = []byte("empty")
}
if !(res.StatusCode == http.StatusAccepted || res.StatusCode == http.StatusNoContent || res.StatusCode == http.StatusOK) {
return errors.Errorf("%s: %s", res.Status, out)
}
return nil
}
g, ctx := errgroup.WithContext(ctx)
inputs := make(chan []byte)
start := time.Now()
for i := 0; i < r.Workers; i++ {
g.Go(func() error {
for {
select {
case <-ctx.Done():
return ctx.Err()
case data, ok := <-inputs:
if !ok {
return nil
}
bo := backoff.NewExponentialBackOff()
bo.MaxElapsedTime = time.Minute
do := func() error { return fn(data) }
if err := backoff.Retry(do, backoff.WithContext(bo, ctx)); err != nil {
return errors.Wrap(err, "retry")
}
if err := r.report(data); err != nil {
return errors.Wrap(err, "report")
}
}
}
})
}
g.Go(func() error {
defer close(inputs)
for d.Decode() {
data := d.Data()
select {
case <-ctx.Done():
return nil
case inputs <- slices.Clone(data):
continue
}
}
return d.Err()
})
if err := g.Wait(); err != nil {
if errors.Is(err, ctx.Err()) {
_ = pb.Exit()
fmt.Println("Canceled")
return nil
}
return err
}
_ = pb.Finish()
fmt.Println("Done")
duration := time.Since(start).Round(time.Millisecond)
fmt.Println("Duration:", duration)
if r.ReportPath != "" {
fmt.Println("Points:", fmtInt(int(r.points.Load())))
pointsPerSecond := float64(r.points.Load()) / duration.Seconds()
fmt.Println("Per second:", fmtInt(int(pointsPerSecond)))
rep := ReplayReport{
Points: int(r.points.Load()),
DurationNanos: duration.Nanoseconds(),
PointsPerSecond: int(pointsPerSecond),
}
data, err := yaml.Marshal(rep)
if err != nil {
return errors.Wrap(err, "marshal report")
}
// #nosec G306
if err := os.WriteFile(r.ReportPath, data, 0644); err != nil {
return errors.Wrap(err, "write report")
}
}
return nil
}
func newReplayCommand() *cobra.Command {
var replay Replay
cmd := &cobra.Command{
Use: "replay",
Aliases: []string{"send"},
Short: "Send recorded requests to remote write server",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return replay.Run(cmd.Context())
},
}
f := cmd.Flags()
f.StringVar(&replay.Target, "target", "http://127.0.0.1:19291", "Target server")
f.StringVarP(&replay.Source, "input", "i", "requests.rwq", "Source file")
f.IntVarP(&replay.Workers, "workers", "j", 8, "Number of workers")
f.StringVar(&replay.Encoding, "encoding", "zstd", "Encoding")
f.StringVar(&replay.ReportPath, "report", "", "Report path")
return cmd
}