-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathconverter.go
466 lines (404 loc) · 13.3 KB
/
converter.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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
/*
*
* k6 - a next-generation load testing tool
* Copyright (C) 2017 Load Impact
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package har
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"net/url"
"sort"
"strings"
"github.com/loadimpact/k6/lib"
"github.com/pkg/errors"
"github.com/tidwall/pretty"
)
// fprint panics when where's an error writing to the supplied io.Writer
// since this will be used on in-memory expandable buffers, that should
// happen only when we run out of memory...
func fprint(w io.Writer, a ...interface{}) int {
n, err := fmt.Fprint(w, a...)
if err != nil {
panic(err.Error())
}
return n
}
// fprintf panics when where's an error writing to the supplied io.Writer
// since this will be used on in-memory expandable buffers, that should
// happen only when we run out of memory...
func fprintf(w io.Writer, format string, a ...interface{}) int {
n, err := fmt.Fprintf(w, format, a...)
if err != nil {
panic(err.Error())
}
return n
}
// TODO: refactor this to have fewer parameters... or just refactor in general...
func Convert(h HAR, options lib.Options, minSleep, maxSleep uint, enableChecks bool, returnOnFailedCheck bool, batchTime uint, nobatch bool, correlate bool, only, skip []string) (result string, convertErr error) {
var b bytes.Buffer
w := bufio.NewWriter(&b)
if returnOnFailedCheck && !enableChecks {
return "", errors.Errorf("return on failed check requires --enable-status-code-checks")
}
if correlate && !nobatch {
return "", errors.Errorf("correlation requires --no-batch")
}
if enableChecks {
fprint(w, "import { group, check, sleep } from 'k6';\n")
} else {
fprint(w, "import { group, sleep } from 'k6';\n")
}
fprint(w, "import http from 'k6/http';\n\n")
fprintf(w, "// Version: %v\n", h.Log.Version)
fprintf(w, "// Creator: %v\n", h.Log.Creator.Name)
if h.Log.Browser != nil {
fprintf(w, "// Browser: %v\n", h.Log.Browser.Name)
}
if h.Log.Comment != "" {
fprintf(w, "// %v\n", h.Log.Comment)
}
fprint(w, "\nexport let options = {\n")
options.ForEachValid("json", func(key string, val interface{}) {
if valJSON, err := json.MarshalIndent(val, " ", " "); err != nil {
convertErr = err
} else {
fprintf(w, " %s: %s,\n", key, valJSON)
}
})
if convertErr != nil {
return "", convertErr
}
fprint(w, "};\n\n")
fprint(w, "export default function() {\n\n")
pages := h.Log.Pages
sort.Sort(PageByStarted(pages))
// Grouping by page and URL filtering
pageEntries := make(map[string][]*Entry)
for _, e := range h.Log.Entries {
// URL filtering
u, err := url.Parse(e.Request.URL)
if err != nil {
return "", err
}
if !IsAllowedURL(u.Host, only, skip) {
continue
}
// Avoid multipart/form-data requests until k6 scripts can support binary data
if e.Request.PostData != nil && strings.HasPrefix(e.Request.PostData.MimeType, "multipart/form-data") {
continue
}
// Create new group o adding page to a existing one
if _, ok := pageEntries[e.Pageref]; !ok {
pageEntries[e.Pageref] = append([]*Entry{}, e)
} else {
pageEntries[e.Pageref] = append(pageEntries[e.Pageref], e)
}
}
for i, page := range pages {
entries := pageEntries[page.ID]
fprintf(w, "\tgroup(\"%s - %s\", function() {\n", page.ID, page.Title)
sort.Sort(EntryByStarted(entries))
if nobatch {
var recordedRedirectURL string
previousResponse := map[string]interface{}{}
fprint(w, "\t\tlet res, redirectUrl, json;\n")
for entryIndex, e := range entries {
var params []string
var cookies []string
var body string
fprintf(w, "\t\t// Request #%d\n", entryIndex)
if e.Request.PostData != nil {
body = e.Request.PostData.Text
}
for _, c := range e.Request.Cookies {
cookies = append(cookies, fmt.Sprintf(`%q: %q`, c.Name, c.Value))
}
if len(cookies) > 0 {
params = append(params, fmt.Sprintf("\"cookies\": {\n\t\t\t\t%s\n\t\t\t}", strings.Join(cookies, ",\n\t\t\t\t\t")))
}
if headers := buildK6Headers(e.Request.Headers); len(headers) > 0 {
params = append(params, fmt.Sprintf("\"headers\": {\n\t\t\t\t\t%s\n\t\t\t\t}", strings.Join(headers, ",\n\t\t\t\t\t")))
}
fprintf(w, "\t\tres = http.%s(", strings.ToLower(e.Request.Method))
if correlate && recordedRedirectURL != "" {
if recordedRedirectURL != e.Request.URL {
return "", errors.Errorf("The har file contained a redirect but the next request did not match that redirect. Possibly a misbehaving client or concurrent requests?")
}
fprintf(w, "redirectUrl")
recordedRedirectURL = ""
} else {
fprintf(w, "%q", e.Request.URL)
}
if e.Request.Method != "GET" {
if correlate && e.Request.PostData != nil && strings.Contains(e.Request.PostData.MimeType, "json") {
requestMap := map[string]interface{}{}
escapedPostdata := strings.Replace(e.Request.PostData.Text, "$", "\\$", -1)
if err := json.Unmarshal([]byte(escapedPostdata), &requestMap); err != nil {
return "", err
}
if len(previousResponse) != 0 {
traverseMaps(requestMap, previousResponse, nil)
}
requestText, err := json.Marshal(requestMap)
if err == nil {
prettyJSONString := string(pretty.PrettyOptions(requestText, &pretty.Options{Width: 999999, Prefix: "\t\t\t", Indent: "\t", SortKeys: true})[:])
fprintf(w, ",\n\t\t\t`%s`", strings.TrimSpace(prettyJSONString))
} else {
return "", err
}
} else {
fprintf(w, ",\n\t\t%q", body)
}
}
if len(params) > 0 {
fprintf(w, ",\n\t\t\t{\n\t\t\t\t%s\n\t\t\t}", strings.Join(params, ",\n\t\t\t"))
}
fprintf(w, "\n\t\t)\n")
if e.Response != nil {
// the response is nil if there is a failed request in the recording, or if responses were not recorded
if enableChecks {
if e.Response.Status > 0 {
if returnOnFailedCheck {
fprintf(w, "\t\tif (!check(res, {\"status is %v\": (r) => r.status === %v })) { return };\n", e.Response.Status, e.Response.Status)
} else {
fprintf(w, "\t\tcheck(res, {\"status is %v\": (r) => r.status === %v });\n", e.Response.Status, e.Response.Status)
}
}
}
if e.Response.Headers != nil {
for _, header := range e.Response.Headers {
if header.Name == "Location" {
fprintf(w, "\t\tredirectUrl = res.headers.Location;\n")
recordedRedirectURL = header.Value
break
}
}
}
responseMimeType := e.Response.Content.MimeType
if correlate &&
strings.Index(responseMimeType, "application/") == 0 &&
strings.Index(responseMimeType, "json") == len(responseMimeType)-4 {
if err := json.Unmarshal([]byte(e.Response.Content.Text), &previousResponse); err != nil {
return "", err
}
fprint(w, "\t\tjson = JSON.parse(res.body);\n")
}
}
}
} else {
batches := SplitEntriesInBatches(entries, batchTime)
fprint(w, "\t\tlet req, res;\n")
for j, batchEntries := range batches {
fprint(w, "\t\treq = [")
for k, e := range batchEntries {
r, err := buildK6RequestObject(e.Request)
if err != nil {
return "", err
}
fprintf(w, "%v", r)
if k != len(batchEntries)-1 {
fprint(w, ",")
}
}
fprint(w, "];\n")
fprint(w, "\t\tres = http.batch(req);\n")
if enableChecks {
for k, e := range batchEntries {
if e.Response.Status > 0 {
if returnOnFailedCheck {
fprintf(w, "\t\tif (!check(res, {\"status is %v\": (r) => r.status === %v })) { return };\n", e.Response.Status, e.Response.Status)
} else {
fprintf(w, "\t\tcheck(res[%v], {\"status is %v\": (r) => r.status === %v });\n", k, e.Response.Status, e.Response.Status)
}
}
}
}
if j != len(batches)-1 {
lastBatchEntry := batchEntries[len(batchEntries)-1]
firstBatchEntry := batches[j+1][0]
t := firstBatchEntry.StartedDateTime.Sub(lastBatchEntry.StartedDateTime).Seconds()
fprintf(w, "\t\tsleep(%.2f);\n", t)
}
}
if i == len(pages)-1 {
// Last page; add random sleep time at the group completion
fprintf(w, "\t\t// Random sleep between %ds and %ds\n", minSleep, maxSleep)
fprintf(w, "\t\tsleep(Math.floor(Math.random()*%d+%d));\n", maxSleep-minSleep, minSleep)
} else {
// Add sleep time at the end of the group
nextPage := pages[i+1]
sleepTime := 0.5
if len(entries) > 0 {
lastEntry := entries[len(entries)-1]
t := nextPage.StartedDateTime.Sub(lastEntry.StartedDateTime).Seconds()
if t >= 0.01 {
sleepTime = t
}
}
fprintf(w, "\t\tsleep(%.2f);\n", sleepTime)
}
}
fprint(w, "\t});\n")
}
fprint(w, "\n}\n")
if err := w.Flush(); err != nil {
return "", err
}
return b.String(), nil
}
func buildK6RequestObject(req *Request) (string, error) {
var b bytes.Buffer
w := bufio.NewWriter(&b)
fprint(w, "{\n")
method := strings.ToLower(req.Method)
if method == "delete" {
method = "del"
}
fprintf(w, `"method": %q, "url": %q`, method, req.URL)
if req.PostData != nil && method != "get" {
postParams, plainText, err := buildK6Body(req)
if err != nil {
return "", err
} else if len(postParams) > 0 {
fprintf(w, `, "body": { %s }`, strings.Join(postParams, ", "))
} else if plainText != "" {
fprintf(w, `, "body": %q`, plainText)
}
}
var params []string
var cookies []string
for _, c := range req.Cookies {
cookies = append(cookies, fmt.Sprintf(`%q: %q`, c.Name, c.Value))
}
if len(cookies) > 0 {
params = append(params, fmt.Sprintf(`"cookies": { %s }`, strings.Join(cookies, ", ")))
}
if headers := buildK6Headers(req.Headers); len(headers) > 0 {
params = append(params, fmt.Sprintf(`"headers": { %s }`, strings.Join(headers, ", ")))
}
if len(params) > 0 {
fprintf(w, `, "params": { %s }`, strings.Join(params, ", "))
}
fprint(w, "}")
if err := w.Flush(); err != nil {
return "", err
}
var buffer bytes.Buffer
err := json.Indent(&buffer, b.Bytes(), "\t\t", "\t")
if err != nil {
return "", err
}
return buffer.String(), nil
}
func buildK6Headers(headers []Header) []string {
var h []string
if len(headers) > 0 {
m := make(map[string]Header)
for _, header := range headers {
name := strings.ToLower(header.Name)
_, exists := m[name]
// Avoid SPDY's, duplicated or cookie headers
if !exists && name[0] != ':' && name != "cookie" {
m[strings.ToLower(header.Name)] = header
h = append(h, fmt.Sprintf("%q: %q", header.Name, header.Value))
}
}
}
return h
}
func buildK6Body(req *Request) ([]string, string, error) {
var postParams []string
if req.PostData.MimeType == "application/x-www-form-urlencoded" && len(req.PostData.Params) > 0 {
for _, p := range req.PostData.Params {
n, err := url.QueryUnescape(p.Name)
if err != nil {
return postParams, "", err
}
v, err := url.QueryUnescape(p.Value)
if err != nil {
return postParams, "", err
}
postParams = append(postParams, fmt.Sprintf(`%q: %q`, n, v))
}
return postParams, "", nil
}
return postParams, req.PostData.Text, nil
}
func traverseMaps(request map[string]interface{}, response map[string]interface{}, path []interface{}) {
if response == nil {
// previous call reached a leaf in the response map so there's no point continuing
return
}
for key, val := range request {
responseVal := response[key]
if responseVal == nil {
// no corresponding value in response map (and the type conversion below would fail so we need an early exit)
continue
}
newPath := append(path, key)
switch concreteVal := val.(type) {
case map[string]interface{}:
traverseMaps(concreteVal, responseVal.(map[string]interface{}), newPath)
case []interface{}:
traverseArrays(concreteVal, responseVal.([]interface{}), newPath)
default:
if responseVal == val {
request[key] = jsObjectPath(newPath)
}
}
}
}
func traverseArrays(requestArray []interface{}, responseArray []interface{}, path []interface{}) {
for i, val := range requestArray {
newPath := append(path, i)
if len(responseArray) <= i {
// requestArray had more entries than responseArray
break
}
responseVal := responseArray[i]
switch concreteVal := val.(type) {
case map[string]interface{}:
traverseMaps(concreteVal, responseVal.(map[string]interface{}), newPath)
case []interface{}:
traverseArrays(concreteVal, responseVal.([]interface{}), newPath)
case string:
if responseVal == val {
requestArray[i] = jsObjectPath(newPath)
}
default:
panic(jsObjectPath(newPath))
}
}
}
func jsObjectPath(path []interface{}) string {
s := "${json"
for _, val := range path {
// this may cause issues with non-array keys with numeric values. test this later.
switch concreteVal := val.(type) {
case int:
s = s + "[" + fmt.Sprint(concreteVal) + "]"
case string:
s = s + "." + concreteVal
}
}
s = s + "}"
return s
}