data.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import http from "k6/http";
  2. import { log, check, group, sleep } from "k6";
  3. import { Rate } from "k6/metrics";
  4. // A custom metric to track failure rates
  5. var failureRate = new Rate("check_failure_rate");
  6. // Options
  7. export let options = {
  8. stages: [
  9. // Linearly ramp up from 1 to 20 VUs during first 30s
  10. { target: 20, duration: "30s" },
  11. // Hold at 50 VUs for the next 1 minute
  12. { target: 20, duration: "1m" },
  13. // Linearly ramp down from 50 to 0 VUs over the last 10 seconds
  14. { target: 0, duration: "10s" }
  15. ],
  16. thresholds: {
  17. // We want the 95th percentile of all HTTP request durations to be less than 500ms
  18. "http_req_duration": ["p(95)<500"],
  19. // Requests with the fast tag should finish even faster
  20. "http_req_duration{fast:yes}": ["p(99)<250"],
  21. // Thresholds based on the custom metric we defined and use to track application failures
  22. "check_failure_rate": [
  23. // Global failure rate should be less than 1%
  24. "rate<0.01",
  25. // Abort the test early if it climbs over 5%
  26. { threshold: "rate<=0.05", abortOnFail: true },
  27. ],
  28. },
  29. };
  30. function rnd(min, max) {
  31. min = Math.ceil(min);
  32. max = Math.floor(max);
  33. return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
  34. }
  35. // Main function
  36. export default function () {
  37. // Control what the data request asks for
  38. let charts = [ "example.random" ]
  39. let chartmin = 0;
  40. let chartmax = charts.length - 1;
  41. let aftermin = 60;
  42. let aftermax = 3600;
  43. let beforemin = 3503600;
  44. let beforemax = 3590000;
  45. let pointsmin = 300;
  46. let pointsmax = 3600;
  47. group("Requests", function () {
  48. // Execute multiple requests in parallel like a browser, to fetch data for the charts. The one taking the longes is the data request.
  49. let resps = http.batch([
  50. ["GET", "http://localhost:19999/api/v1/info", { tags: { fast: "yes" } }],
  51. ["GET", "http://localhost:19999/api/v1/charts", { tags: { fast: "yes" } }],
  52. ["GET", "http://localhost:19999/api/v1/data?chart="+charts[rnd(chartmin,chartmax)]+"&before=-"+rnd(beforemin,beforemax)+"&after=-"+rnd(aftermin,aftermax)+"&points="+rnd(pointsmin,pointsmax)+"&format=json&group=average&gtime=0&options=ms%7Cflip%7Cjsonwrap%7Cnonzero&_="+rnd(1,1000000000000), { }],
  53. ["GET", "http://localhost:19999/api/v1/alarms", { tags: { fast: "yes" } }]
  54. ]);
  55. // Combine check() call with failure tracking
  56. failureRate.add(!check(resps, {
  57. "status is 200": (r) => r[0].status === 200 && r[1].status === 200
  58. }));
  59. });
  60. sleep(Math.random() * 2 + 1); // Random sleep between 1s and 3s
  61. }