負荷試験ツールのk6が良さそう

またもやisucon本から。
前回はこちら(アクセスログの集計ツールのalpが良い )。

本題

負荷テストツールとしては、Apache JMeterApache Bench(ab)辺りをよく使っていましたが、 isucon本で紹介されているk6の感触が良かったので、ご紹介です。 installationはmacだとbrewでサクッと入るので省略。

使い方

シナリオをjsで書いて、コマンドで実行するだけです。
本書で紹介されていたab的な使い方だと、以下のような感じです。

import http from "k6/http";

const BASE_URL = "http://localhost";

export default function() {
  http.get(`${BASE_URL}`);
}
# 並列度1で30秒実行
$ k6 run --vus 1 --duration 30s ab.js

実行結果。 Requests per secondにあたるのが、http_reqs。Time per request(レスポンスタイム)にあたるのが、http_reeq_durationのavg

もう少し複雑な例

ログイン、画面遷移、コメントをPOSTするような処理も以下のように書けます。

// comment.js
import http from "k6/http";
import { check } from "k6";
import { parseHTML } from "k6/html";

import { url } from "./config.js";

export default function() {
  // ログイン
  const login_res = http.post(url("/login"), {
    account_name: "terra",
    password: "terraterra",
  });

  check(login_res, {
    "is status 200": (r) => r.status === 200,
  });

  // ユーザー画面へ遷移しResponseを取得
  const res = http.get(url("/@terra"));
  const doc = parseHTML(res.body);
  const token = doc.find('input[name="csrf_token"]').first().attr("value");
  const post_id = doc.find('input[name="post_id"]').first().attr("value");

  // コメント
  const comment_res = http.post(url("/comment"), {
    post_id: post_id,
    csrf_token: token,
    comment: "Hello k6!",
  });
  check(comment_res, {
    "is status 200": (r) => r.status === 200,
  });
}
// config.js
const BASE_URL = "http://localhost";

export function url(path) {
  return `${BASE_URL}${path}`;
}
$ k6 run --vus 1 comment.js

check() を使ってますが、これがあると試行回数と結果が出力されるようになります。

default ✓ [======================================] 1 VUs  00m01.6s/10m0s  1/1 iters, 1 per VU

     ✓ is status 200

     checks.........................: 100.00% ✓ 2        ✗ 0

感想

JMeterとか独特のUIですし、こういう風にscirptでチャチャっと書いていけるのは、なかなか良いです。
実際に利用するとなると環境用意するのが若干面倒だったりするので、sassで提供されてると嬉しいよなと思ってググってみると、やはりありました。 Plan & Pricing | k6 Cloud
お値段は、安いやつだと $89/mo なので結構現実的かもしれません。

See Also

アクセスログの集計ツールのalpが良い - rochefort's blog