Skip to content

Instantly share code, notes, and snippets.

@GavinRay97
Created July 24, 2020 15:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GavinRay97/b57094686f64ad4591c55eb7b9dd5cac to your computer and use it in GitHub Desktop.
Save GavinRay97/b57094686f64ad4591c55eb7b9dd5cac to your computer and use it in GitHub Desktop.
private async _runK6(metadata: RunK6Metadata, config: K6Options) {
const { queryName, outputFile } = metadata
// If "debug" true, log all HTTP responses
if (this.config.debug) config.httpDebug = 'full'
// Write the K6 configuration JSON to a temp file, to pass as CLI flag
const tmpConfig = path.join(__dirname, 'tmp', `${queryName}_config.json`)
await fs.outputJSON(tmpConfig, config)
// outPath is where the JSON report stats will go, scriptFile points K6 to the JS script for the load test
const outPath = path.join(this.reportPath, outputFile)
const scriptFile = path.join(__dirname, 'k6', 'loadScript.js')
// Make sure the directory exists, or K6 will fail when writing
await fs.ensureFile(outPath)
// Invoke 'k6 run <scriptFile path> --config <tmpConfig path> --summary-export <outPath>'
const baseOpts: string[] = []
baseOpts.push('run', scriptFile)
baseOpts.push('--config', tmpConfig)
baseOpts.push('--out', 'json=k6_raw_stats.json')
baseOpts.push('--summary-export', outPath)
const k6 = cp.spawnSync(this.k6BinaryPath, baseOpts, {
cwd: __dirname,
stdio: 'inherit',
})
if (k6.error) console.log('ERROR RUNNING K6:', k6.error)
// Create a line-reader to parse each entry of JSONL logs
const fileStream = fs.createReadStream('k6_raw_stats.json')
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity,
})
const histogram = hdr.build()
let stats: K6Point[] = []
for await (const line of rl) {
const stat: K6Metric | K6Point = JSON.parse(line)
if (stat.type != 'Point') continue
if (stat.metric != 'http_req_duration') continue
if (Number(stat.data.tags.status) < 200) continue
stats.push(stat)
histogram.recordValue(stat.data.value)
}
fs.writeJSONSync('k6_parsed_stats.json', stats)
console.log(histogram.summary)
console.log(histogram.outputPercentileDistribution())
// Remove the temp config file with the K6 run parameters
await fs.remove(tmpConfig)
// Return the JSON output stats produced by K6 for bench
const jsonStats = fs.readJSONSync(outPath)
return jsonStats
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment