Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ jobs:
cache: true
- name: gofmt
run: test -z "$(gofmt -l .)" || { gofmt -l .; exit 1; }
# The gRPC hooks exist only in the patched k6 (see patches/); the code
# using them needs -tags k6patched, so these steps build against stock k6
# and the patched-build job compiles the hooked code.
- name: go vet
run: go vet ./...
- name: go test
Expand All @@ -36,3 +39,37 @@ jobs:
run: bash scripts/check-source-md.sh
- name: Release tag script tests
run: bash scripts/tag-release_test.sh

patched-build:
# Builds the real binary (k6 patches applied, every extension linked) and
# runs the release gate on it, so a patch that no longer applies or hooked
# code that no longer compiles fails the PR.
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
persist-credentials: false
- uses: actions/setup-go@d35c59abb061a4a6fb18e82ac0862c26744d6ab5 # v5.5.0
with:
go-version: "1.26.11"
cache: true
- name: Install xk6
run: go install go.k6.io/xk6/cmd/xk6@v1.4.12
- name: Build k6 (linux/amd64)
run: GOOS=linux GOARCH=amd64 CGO_ENABLED=0 ./build.sh --output dist/k6
- name: Release gate
run: bash scripts/release-gate.sh --binary dist/k6 --arch amd64
# The hooked code (-tags k6patched) only compiles against the patched k6 that
# build.sh left at its fixed path; test it there too, so the pacer and capture
# hooks are exercised and not only linked. go.mod is edited in the runner only.
- name: go test (k6 patch)
run: |
k6v="$(jq -r .k6Version extensions.json)"
cd "/tmp/xk6-load-toolkit/k6-${k6v}-patched"
go test -race -count=1 ./internal/lib/netext/grpcext/
- name: go test (patched k6)
run: |
k6v="$(jq -r .k6Version extensions.json)"
go mod edit -replace "go.k6.io/k6/v2=/tmp/xk6-load-toolkit/k6-${k6v}-patched"
go vet -tags k6patched ./...
go test -race -count=1 -tags k6patched ./...
171 changes: 157 additions & 14 deletions README.md

Large diffs are not rendered by default.

25 changes: 19 additions & 6 deletions SOURCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,21 @@ Read this file at that tag (or commit):

| Component | Go module | Version | Commit | Licence | Source |
|---|---|---|---|---|---|
| k6 | `go.k6.io/k6/v2` | v2.2.0 | `00a9a1b7f552d6bb4337278b10ae25aac0f4e666` | AGPL-3.0 | <https://github.com/grafana/k6/tree/v2.2.0> |
| k6 | `go.k6.io/k6/v2` | v2.2.0 | `00a9a1b7f552d6bb4337278b10ae25aac0f4e666` | AGPL-3.0 | <https://github.com/grafana/k6/tree/v2.2.0>, with the patches below |
| xk6-load-toolkit | `github.com/browserstack/xk6-load-toolkit` | the image's `org.opencontainers.image.version` label | the `commit` in `build-info.json` (also the `org.opencontainers.image.revision` label) | AGPL-3.0 | <https://github.com/browserstack/xk6-load-toolkit/tree/<tag>> |

### k6 patches (`k6Patches` in `extensions.json`)

The binary links k6 with these patches applied, in this order, by `build.sh`
(`git apply` on the pinned k6 source, then `xk6 build --replace`). Both files
are in this repository, so the patched k6 source is the k6 commit above plus
these files.

| Patch | What it changes |
|---|---|
| [`patches/k6-grpc-deadline.patch`](patches/k6-grpc-deadline.patch) | Pushes a finished gRPC call's `grpc_req_duration` sample against the VU context instead of the call's own, so calls that end with `DEADLINE_EXCEEDED` are recorded (stock k6 drops them, because the deadline cancels the call's context). |
| [`patches/k6-grpc-capture.patch`](patches/k6-grpc-capture.patch) | Adds the `lib/netext/grpccapture` package: a hook an extension can register to observe every gRPC call's stats (used by the `grpcCapture` capability) and a pacer called with the method name before each unary call and stream open (used by the throughput limiter). A pacer error that is the call's context ending fails that call; any other pacer error aborts the test run through k6's test-run context (exit code 104). With nothing registered each call pays one atomic load. The patch carries its own test (`internal/lib/netext/grpcext/pace_test.go`). |

### Third-party extensions (15, pinned in `extensions.json`)

| Extension | Go module | Version | Commit | Licence | Source |
Expand Down Expand Up @@ -93,9 +105,10 @@ All in this repository at the same commit:

| File | Role |
|---|---|
| [`extensions.json`](extensions.json) | The manifest: the k6 version and every extension with its pinned version. |
| [`build.sh`](build.sh) | Turns the manifest into `xk6 build --k6-version … --with <module>@<version> …` and runs it with CGO off. |
| [`scripts/release-gate.sh`](scripts/release-gate.sh) | Reads the binary's `go version -m` output and fails unless every pin above is linked at exactly its version. |
| [`extensions.json`](extensions.json) | The manifest: the k6 version, the k6 patches and every extension with its pinned version. |
| [`build.sh`](build.sh) | Applies the k6 patches to a copy of the pinned k6 source at `/tmp/xk6-load-toolkit/k6-<version>-patched`, turns the manifest into `xk6 build --k6-version … --with <module>@<version> … --replace go.k6.io/k6/v2=<that directory> --build-flags -trimpath --build-flags "-ldflags=-s -w" --build-flags -tags=k6patched` and runs it with CGO off. |
| [`patches/`](patches) | The k6 patches listed above. |
| [`scripts/release-gate.sh`](scripts/release-gate.sh) | Reads the binary's `go version -m` output and fails unless every pin above is linked at exactly its version, and k6 is replaced by exactly the patched copy. |
| This file | The builder stage below, the toolchain pins and the component list. |

### Builder stage
Expand Down Expand Up @@ -153,6 +166,6 @@ RUN GOOS=linux GOARCH="$TARGETARCH" CGO_ENABLED=0 ./build.sh --output /out/k6 &&

## Keeping this file current

A change to `extensions.json`, to the Go image or `go-version`, or to the xk6
version must update this file in the same commit, so that this file at any
A change to `extensions.json`, to a file in `patches/`, to the Go image or
`go-version`, or to the xk6 version must update this file in the same commit, so that this file at any
commit describes the binaries built from that commit.
60 changes: 58 additions & 2 deletions build.sh
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,19 @@
# script, --k6-version the manifest's "k6Version", --output ./dist/k6.
# GOOS / GOARCH from the environment select the target; CGO is always off.
#
# "k6Patches" (optional) lists repo-relative patch files applied to the k6 source
# before the build: the pinned k6 module is fetched through the Go module proxy,
# copied to a fixed directory, patched with `git apply`, and handed to xk6 with
# --replace, with -tags k6patched so the code that uses the patched k6's hooks
# is compiled in. A patch that no longer applies (k6 version drift) fails the
# build, and so does a binary that was not linked against the patched copy.
#
# Each manifest entry has exactly one of:
# "repoPath": a directory relative to --repo-root -> --with <module>=<dir>
# "version": a module version -> --with <module>@<version>
# An entry with both, or neither, fails the build: a pin must never be ignored.
#
# Requires xk6, jq and go on PATH.
# Requires xk6, jq and go on PATH (and git when k6Patches is set).
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
Expand Down Expand Up @@ -72,14 +79,56 @@ done < <(jq -r '.extensions[] | [.name, .module, (.repoPath // ""), (.version //

[[ ${#WITH_ARGS[@]} -gt 0 ]] || { echo "[build] manifest is empty, nothing to build" >&2; exit 1; }

K6_PATCHES=()
while IFS= read -r patch_path; do
[[ -n "$patch_path" ]] && K6_PATCHES+=("$patch_path")
done < <(jq -r '(.k6Patches // [])[]' "$MANIFEST")

REPLACE_ARGS=()
PATCHED_K6_DIR=""
if [[ ${#K6_PATCHES[@]} -gt 0 ]]; then
command -v git >/dev/null 2>&1 || { echo "[build] ERROR: git is required to apply k6Patches" >&2; exit 1; }
command -v go >/dev/null 2>&1 || { echo "[build] ERROR: go is required to apply k6Patches" >&2; exit 1; }
k6_major="${K6_VERSION#v}"
k6_major="${k6_major%%.*}"
K6_MODULE="go.k6.io/k6"
if [[ "$k6_major" =~ ^[0-9]+$ && "$k6_major" -ge 2 ]]; then
K6_MODULE="go.k6.io/k6/v${k6_major}"
fi
k6_src_dir="$(go mod download -json "${K6_MODULE}@${K6_VERSION}" | jq -r '.Dir // empty')"
[[ -n "$k6_src_dir" && -d "$k6_src_dir" ]] || {
echo "[build] ERROR: could not download ${K6_MODULE}@${K6_VERSION} source" >&2; exit 1; }
# A fixed path, not a temp dir: the replacement directory is recorded in the
# binary's build info, so a random path would make every build differ.
PATCHED_K6_DIR="/tmp/xk6-load-toolkit/k6-${K6_VERSION}-patched"
rm -rf "$PATCHED_K6_DIR"
mkdir -p "$(dirname "$PATCHED_K6_DIR")"
cp -R "$k6_src_dir" "$PATCHED_K6_DIR"
chmod -R u+w "$PATCHED_K6_DIR"
for patch_path in "${K6_PATCHES[@]}"; do
patch_file="${REPO_ROOT}/${patch_path}"
Comment thread
dheeren-gaud marked this conversation as resolved.
Resolved
[[ -f "$patch_file" ]] || { echo "[build] ERROR: patch ${patch_path} not found at ${patch_file}" >&2; exit 1; }
if ! (cd "$PATCHED_K6_DIR" && git apply --check -p1 "$patch_file"); then
echo "[build] ERROR: patch ${patch_path} does not apply to k6 ${K6_VERSION}" >&2
exit 1
fi
(cd "$PATCHED_K6_DIR" && git apply -p1 "$patch_file")
echo "[build] patched k6 ${K6_VERSION} with ${patch_path}"
done
REPLACE_ARGS=(--replace "${K6_MODULE}=${PATCHED_K6_DIR}")
# The code that uses the patched k6's hooks builds only with -tags k6patched. --build-flags
# replaces xk6's defaults, so they are repeated here unchanged.
REPLACE_ARGS+=(--build-flags -trimpath --build-flags "-ldflags=-s -w" --build-flags -tags=k6patched)
fi

mkdir -p "$(dirname "$OUTPUT")"
echo "[build] k6=${K6_VERSION} GOOS=${GOOS:-host} GOARCH=${GOARCH:-host} output=${OUTPUT} extensions=$((${#WITH_ARGS[@]} / 2))"

# xk6 reads K6_VERSION from the environment as its --k6-version flag, so pass
# the version only as the flag, never also as a positional argument.
# Module-proxy fetches fail transiently; retry, resuming from the module cache.
attempt=1
until CGO_ENABLED=0 xk6 build --verbose --k6-version "$K6_VERSION" "${WITH_ARGS[@]}" --output "$OUTPUT"; do
until CGO_ENABLED=0 xk6 build --verbose --k6-version "$K6_VERSION" "${WITH_ARGS[@]}" ${REPLACE_ARGS[@]+"${REPLACE_ARGS[@]}"} --output "$OUTPUT"; do
if [[ "$attempt" -ge 3 ]]; then
echo "[build] FAILED after ${attempt} attempts" >&2
exit 1
Expand All @@ -89,4 +138,11 @@ until CGO_ENABLED=0 xk6 build --verbose --k6-version "$K6_VERSION" "${WITH_ARGS[
attempt=$((attempt + 1))
done

# A replace xk6 dropped would ship stock k6 with exit 0; the build info names the replacement.
if [[ -n "$PATCHED_K6_DIR" ]] &&
! go version -m "$OUTPUT" | awk -v dir="$PATCHED_K6_DIR" '$1 == "=>" && $2 == dir { found = 1 } END { exit !found }'; then
echo "[build] ERROR: ${OUTPUT} was not built against the patched k6 (${PATCHED_K6_DIR})" >&2
exit 1
fi

echo "[build] done -> $OUTPUT"
4 changes: 4 additions & 0 deletions extensions.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
{
"k6Version": "v2.2.0",
"k6Patches": [
"patches/k6-grpc-deadline.patch",
"patches/k6-grpc-capture.patch"
],
"extensions": [
{
"name": "load-toolkit",
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ require (
github.com/go-logr/logr v1.4.3 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-sourcemap/sourcemap v2.1.4+incompatible // indirect
github.com/golang/protobuf v1.5.4 // indirect
github.com/google/pprof v0.0.0-20260115054156-294ebfa9ad83 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/grafana/sobek v0.0.0-20260727154728-7781506a890f // indirect
Expand Down
69 changes: 58 additions & 11 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (

"go.k6.io/k6/v2/errext/exitcodes"

"github.com/browserstack/xk6-load-toolkit/internal/grpccapture"
"github.com/browserstack/xk6-load-toolkit/internal/sink"
tagfilter "github.com/browserstack/xk6-load-toolkit/internal/tag-filter"
"github.com/browserstack/xk6-load-toolkit/internal/throughput"
Expand Down Expand Up @@ -43,6 +44,8 @@ type Config struct {
Throughput *throughput.Config `json:"throughput"`
TagFilter *tagfilter.Config `json:"tagFilter"`
Sink *sink.Config `json:"sink"`
// GRPCCapture records a sample of gRPC calls; needs the k6 gRPC hooks (see README).
GRPCCapture *grpccapture.Config `json:"grpcCapture"`
}

// EnvConfig lists extra variables removed from the process environment in init().
Expand All @@ -53,12 +56,13 @@ type EnvConfig struct {
// The configuration is read once, in init(), because k6 copies the process
// environment into the script's __ENV before any extension code runs again.
var (
loadedConfig *Config
configErr error
loadedConfig *Config
throughputPresent bool
configErr error
)

func init() {
loadedConfig, configErr = loadFromEnv()
loadedConfig, throughputPresent, configErr = loadFromEnv()
if errors.Is(configErr, errUnreadable) {
// Nothing in the document could be read, so the variables it meant to hide
// may still be set. Stop now, before k6 runs any script code.
Expand All @@ -70,6 +74,11 @@ func init() {
// Loaded returns the configuration read in init(), or the startup error.
func Loaded() (*Config, error) { return loadedConfig, configErr }

// ThroughputPresent reports whether the document has a throughput section, whether or not it
// (or another section) failed to load. With no section, nothing that only the throughput
// capability does may fail because another section is bad.
func ThroughputPresent() bool { return throughputPresent }

// Throughput returns the throughput section read in init(), or the startup error.
func Throughput() (*throughput.Config, error) {
if configErr != nil {
Expand All @@ -78,6 +87,14 @@ func Throughput() (*throughput.Config, error) {
return loadedConfig.Throughput, nil
}

// GRPCCapture returns the grpcCapture section read in init(), or the startup error.
func GRPCCapture() (*grpccapture.Config, error) {
if configErr != nil {
return nil, configErr
}
return loadedConfig.GRPCCapture, nil
}

// TagFilter returns the tagFilter section read in init(), or the startup error.
func TagFilter() (*tagfilter.Config, error) {
if configErr != nil {
Expand All @@ -90,8 +107,8 @@ func TagFilter() (*tagfilter.Config, error) {
// init() aborts the process on it. Its message is errStartup's.
var errUnreadable = fmt.Errorf("%w", errStartup)

// loadFromEnv reads, validates and unsets the configuration. An absent
// variable means every capability is off.
// loadFromEnv reads, validates and unsets the configuration, and reports whether
// it has a throughput section. An absent variable means every capability is off.
//
// The keys in env.unset are removed before strict validation, by a lenient
// pass that ignores every other field and anything after the document, so a
Expand All @@ -100,29 +117,54 @@ var errUnreadable = fmt.Errorf("%w", errStartup)
// any script code runs. The producer of the variable must emit valid JSON,
// with env before the other sections so its keys are read even when a later
// field is malformed.
func loadFromEnv() (*Config, error) {
func loadFromEnv() (cfg *Config, hasThroughput bool, err error) {
raw, present := os.LookupEnv(ConfigEnv)
diagnostics := os.Getenv(DiagnosticsEnv)
_ = os.Unsetenv(ConfigEnv)
_ = os.Unsetenv(DiagnosticsEnv)
if !present {
return &Config{Version: SchemaVersion}, nil
return &Config{Version: SchemaVersion}, false, nil
}

if err := unsetListed(raw); err != nil {
writeDiagnostics(diagnostics, fmt.Errorf("decode: %w", err))
return nil, errUnreadable
return nil, false, errUnreadable
}

cfg, err := Parse([]byte(raw))
cfg, err = Parse([]byte(raw))
if cfg != nil && cfg.Env != nil {
unsetAll(cfg.Env.Unset) // backstop: the list as the strict pass read it
}
if err != nil {
writeDiagnostics(diagnostics, err)
return nil, errStartup
return nil, hasSection(raw, "throughput"), errStartup
}
return cfg, cfg.Throughput != nil, nil
}

// hasSection reports whether the top-level object has a non-null value under name, matched
// the way the strict decode matches field names (case-insensitively, the last duplicate wins).
// It reads a document the strict decode rejected, so it skips every value without checking it.
func hasSection(raw, name string) bool {
dec := json.NewDecoder(strings.NewReader(raw))
if tok, err := dec.Token(); err != nil || tok != json.Delim('{') {
return false
}
return cfg, nil
found := false
for dec.More() {
keyTok, err := dec.Token()
if err != nil {
return found
}
var value json.RawMessage
if err := dec.Decode(&value); err != nil {
return found
}
if key, _ := keyTok.(string); strings.EqualFold(key, name) {
found = !bytes.Equal(bytes.TrimSpace(value), []byte("null"))
}
}
return found
}

// unsetListed walks the top-level object and unsets env.unset as soon as it is
Expand Down Expand Up @@ -226,6 +268,11 @@ func (c *Config) Validate() error {
return err
}
}
if c.GRPCCapture != nil {
if err := c.GRPCCapture.Validate(); err != nil {
return err
}
}
if c.Sink != nil {
return c.Sink.Validate()
}
Expand Down
Loading
Loading