├── .gitignore
├── .dockerignore
├── etc
├── dummyweb.go
└── requests.jsonl
├── .claude
└── settings.local.json
├── tools
└── linkerdxripley
│ ├── pkg
│ ├── linkerd
│ │ └── request.go
│ └── converter
│ │ ├── converter.go
│ │ └── converter_test.go
│ ├── go.mod
│ ├── testdata
│ └── linkerd_sample.jsonl
│ ├── main.go
│ ├── go.sum
│ ├── main_test.go
│ └── README.md
├── go.mod
├── .github
└── workflows
│ ├── goreleaser.yaml
│ └── ci.yaml
├── Dockerfile
├── pkg
├── request_test.go
├── request.go
├── client.go
├── pace_test.go
├── replay.go
├── pace.go
├── replay_integration_test.go
├── metrics.go
└── metrics_test.go
├── .goreleaser.yaml
├── CLAUDE.md
├── go.sum
├── main.go
├── README.md
└── LICENSE
/.gitignore:
--------------------------------------------------------------------------------
1 | ripley
2 | .idea/
3 | dist/
4 |
--------------------------------------------------------------------------------
/.dockerignore:
--------------------------------------------------------------------------------
1 | # Documentation
2 | *.md
3 | README.md
4 | CLAUDE.md
5 | LICENSE
6 |
7 | # Git
8 | .git
9 | .gitignore
10 | .gitattributes
11 |
12 | # IDE and editor files
13 | .vscode
14 | .idea
15 | *.swp
16 | *.swo
17 | *~
18 | .DS_Store
19 |
20 | # CI/CD
21 | .github
22 | .gitlab-ci.yml
23 | .travis.yml
24 |
25 | # Test data and test files
26 | *_test.go
27 | testdata
28 |
29 | # Development scripts
30 | Makefile
31 | scripts
32 |
33 | # Misc
34 | *.log
35 | tmp
36 | temp
37 |
--------------------------------------------------------------------------------
/etc/dummyweb.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "log"
6 | "math/rand"
7 | "net/http"
8 | "time"
9 | )
10 |
11 | var count int
12 |
13 | func handler(w http.ResponseWriter, r *http.Request) {
14 | count++
15 | time.Sleep(time.Duration(rand.Intn(250)) * time.Millisecond)
16 | _, _ = w.Write([]byte("hi\n"))
17 | }
18 |
19 | func main() {
20 | // Crude RPS reporting
21 | go func() {
22 | for {
23 | fmt.Printf("rps: %d\n", count)
24 | count = 0
25 | time.Sleep(time.Second)
26 | }
27 | }()
28 |
29 | http.HandleFunc("/", handler)
30 | log.Fatal(http.ListenAndServe(":8080", nil))
31 | }
32 |
--------------------------------------------------------------------------------
/.claude/settings.local.json:
--------------------------------------------------------------------------------
1 | {
2 | "permissions": {
3 | "allow": [
4 | "Bash(gh run list:*)",
5 | "Bash(go test:*)",
6 | "Bash(go build:*)",
7 | "Bash(for i in {1..10})",
8 | "Bash(do echo \"Run $i:\")",
9 | "Bash(done)",
10 | "Bash(docker run:*)",
11 | "Bash(docker images:*)",
12 | "Bash(git log:*)",
13 | "Bash(git ls-tree:*)",
14 | "Bash(go get:*)",
15 | "Bash(go mod tidy:*)",
16 | "Bash(go run:*)",
17 | "Bash(curl:*)",
18 | "Bash(cat:*)",
19 | "Bash(./ripley:*)"
20 | ],
21 | "deny": [],
22 | "ask": []
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/tools/linkerdxripley/pkg/linkerd/request.go:
--------------------------------------------------------------------------------
1 | package linkerd
2 |
3 | type Request struct {
4 | ClientAddr string `json:"client.addr"`
5 | ClientID string `json:"client.id"`
6 | Host string `json:"host"`
7 | Method string `json:"method"`
8 | ProcessingNs string `json:"processing_ns"`
9 | RequestBytes string `json:"request_bytes"`
10 | Status int `json:"status"`
11 | Timestamp string `json:"timestamp"`
12 | TotalNs string `json:"total_ns"`
13 | TraceID string `json:"trace_id"`
14 | URI string `json:"uri"`
15 | UserAgent string `json:"user_agent"`
16 | Version string `json:"version"`
17 | }
18 |
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/loveholidays/ripley
2 |
3 | go 1.23.0
4 |
5 | toolchain go1.24.1
6 |
7 | require github.com/prometheus/client_golang v1.23.2
8 |
9 | require (
10 | github.com/beorn7/perks v1.0.1 // indirect
11 | github.com/cespare/xxhash/v2 v2.3.0 // indirect
12 | github.com/kr/text v0.2.0 // indirect
13 | github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
14 | github.com/prometheus/client_model v0.6.2 // indirect
15 | github.com/prometheus/common v0.66.1 // indirect
16 | github.com/prometheus/procfs v0.16.1 // indirect
17 | go.yaml.in/yaml/v2 v2.4.2 // indirect
18 | golang.org/x/sys v0.35.0 // indirect
19 | google.golang.org/protobuf v1.36.8 // indirect
20 | )
21 |
--------------------------------------------------------------------------------
/tools/linkerdxripley/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/loveholidays/ripley/tools/linkerdxripley
2 |
3 | go 1.23.0
4 |
5 | toolchain go1.24.1
6 |
7 | require github.com/loveholidays/ripley v0.0.0
8 |
9 | require (
10 | github.com/beorn7/perks v1.0.1 // indirect
11 | github.com/cespare/xxhash/v2 v2.3.0 // indirect
12 | github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
13 | github.com/prometheus/client_golang v1.23.2 // indirect
14 | github.com/prometheus/client_model v0.6.2 // indirect
15 | github.com/prometheus/common v0.66.1 // indirect
16 | github.com/prometheus/procfs v0.16.1 // indirect
17 | go.yaml.in/yaml/v2 v2.4.2 // indirect
18 | golang.org/x/sys v0.35.0 // indirect
19 | google.golang.org/protobuf v1.36.8 // indirect
20 | )
21 |
22 | replace github.com/loveholidays/ripley => ../..
23 |
--------------------------------------------------------------------------------
/.github/workflows/goreleaser.yaml:
--------------------------------------------------------------------------------
1 | name: goreleaser
2 |
3 | on:
4 | push:
5 | tags:
6 | - '*'
7 |
8 | jobs:
9 | goreleaser:
10 | runs-on: ubuntu-latest
11 | steps:
12 | - name: Login to Docker Hub
13 | uses: docker/login-action@v1
14 | with:
15 | username: ${{ secrets.DOCKERHUB_USERNAME }}
16 | password: ${{ secrets.DOCKERHUB_TOKEN }}
17 | -
18 | name: Checkout
19 | uses: actions/checkout@v2
20 | with:
21 | fetch-depth: 0
22 | -
23 | name: Set up Go
24 | uses: actions/setup-go@v2
25 | with:
26 | go-version: 1.22
27 | -
28 | name: Run GoReleaser
29 | uses: goreleaser/goreleaser-action@v2
30 | with:
31 | distribution: goreleaser
32 | version: latest
33 | args: release --clean
34 | env:
35 | GITHUB_TOKEN: ${{ secrets.TOKEN_GORELEASER }}
36 |
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | # Stage 1: Build the binaries
2 | FROM golang:1.23-alpine AS builder
3 |
4 | # Install build dependencies
5 | RUN apk add --no-cache git
6 |
7 | WORKDIR /build
8 |
9 | # Copy go mod files first for better caching
10 | COPY go.mod go.sum ./
11 | RUN go mod download
12 |
13 | # Copy source code
14 | COPY . .
15 |
16 | # Build the main ripley binary
17 | RUN go build -o ripley main.go
18 |
19 | # Build the linkerdxripley tool (separate module)
20 | RUN cd tools/linkerdxripley && go build -o ../../linkerdxripley .
21 |
22 | # Stage 2: Create the final minimal image
23 | FROM alpine:latest
24 |
25 | # Install ca-certificates for HTTPS connections
26 | RUN apk add --no-cache ca-certificates
27 |
28 | WORKDIR /app/
29 |
30 | # Copy the built binaries from the builder stage
31 | COPY --from=builder /build/ripley /app/ripley
32 | COPY --from=builder /build/linkerdxripley /app/linkerdxripley
33 |
34 | # Ensure binaries are executable
35 | RUN chmod +x /app/ripley /app/linkerdxripley
36 |
37 | ENTRYPOINT ["/app/ripley"]
38 |
--------------------------------------------------------------------------------
/tools/linkerdxripley/testdata/linkerd_sample.jsonl:
--------------------------------------------------------------------------------
1 | {"client.addr":"192.168.1.100:12345","client.id":"test-service.default.serviceaccount.identity.linkerd.cluster.local","host":"api-service.test.svc.cluster.local","method":"GET","processing_ns":"50000","request_bytes":"0","status":200,"timestamp":"2025-09-03T15:30:32.928995068Z","total_ns":"2500000","trace_id":"abc123","uri":"http://api-service.test.svc.cluster.local/api/v1/data?id=12345","user_agent":"TestClient/1.0","version":"HTTP/2.0"}
2 | {"client.addr":"192.168.1.101:54321","client.id":"another-service.default.serviceaccount.identity.linkerd.cluster.local","host":"api-service.test.svc.cluster.local","method":"POST","processing_ns":"75000","request_bytes":"256","status":201,"timestamp":"2025-09-03T15:30:33.123456789Z","total_ns":"3000000","trace_id":"def456","uri":"http://api-service.test.svc.cluster.local/api/v1/create","user_agent":"TestClient/2.0","version":"HTTP/2.0"}
3 | {"client.addr":"192.168.1.102:67890","client.id":"web-frontend.default.serviceaccount.identity.linkerd.cluster.local","host":"search-service.test.svc.cluster.local","method":"GET","processing_ns":"25000","request_bytes":"0","status":200,"timestamp":"2025-09-03T15:30:34.987654321Z","total_ns":"1500000","trace_id":"ghi789","uri":"http://search-service.test.svc.cluster.local/search?q=test&limit=10","user_agent":"WebBrowser/3.0","version":"HTTP/1.1"}
--------------------------------------------------------------------------------
/etc/requests.jsonl:
--------------------------------------------------------------------------------
1 | {"url": "http://localhost:8080/", "method": "GET", "timestamp": "2021-11-08T18:59:50.9Z"}
2 | {"url": "http://localhost:8080/", "method": "GET", "timestamp": "2021-11-08T18:59:51.9Z"}
3 | {"url": "http://localhost:8080/", "method": "GET", "timestamp": "2021-11-08T18:59:52.9Z"}
4 | {"url": "http://localhost:8080/", "method": "GET", "timestamp": "2021-11-08T18:59:53.9Z"}
5 | {"url": "http://localhost:8080/", "method": "GET", "timestamp": "2021-11-08T18:59:54.9Z"}
6 | {"url": "http://localhost:8080/", "method": "GET", "timestamp": "2021-11-08T18:59:55.9Z"}
7 | {"url": "http://localhost:8080/", "method": "GET", "timestamp": "2021-11-08T18:59:56.9Z"}
8 | {"url": "http://localhost:8080/", "method": "GET", "timestamp": "2021-11-08T18:59:57.9Z"}
9 | {"url": "http://localhost:8080/", "method": "POST", "body": "{\"foo\": \"bar\"}", "headers": {"Accept": "text/plain"}, "timestamp": "2021-11-08T18:59:58.9Z"}
10 | {"url": "http://localhost:8080/", "method": "GET", "headers": {"Accept": "text/plain"}, "timestamp": "2021-11-08T18:59:59.9Z"}
11 | {"url": "http://localhost:8080/", "method": "HEAD", "timestamp": "2021-11-08T19:00:00.00Z"}
12 | {"url": "http://localhost:8080/", "method": "OPTIONS", "timestamp": "2021-11-08T19:00:00.01Z"}
13 | {"url": "http://localhost:8080/", "method": "TRACE", "timestamp": "2021-11-08T19:00:00.02Z"}
14 | {"url": "http://localhost:8080/", "method": "GET", "timestamp": "2021-11-08T19:00:00.04Z"}
--------------------------------------------------------------------------------
/pkg/request_test.go:
--------------------------------------------------------------------------------
1 | /*
2 | ripley
3 | Copyright (C) 2021 loveholidays
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU General Public License as published by
7 | the Free Software Foundation, either version 3 of the License, or
8 | (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU General Public License for more details.
14 |
15 | You should have received a copy of the GNU General Public License
16 | along with this program. If not, see .
17 | */
18 |
19 | package ripley
20 |
21 | import (
22 | "testing"
23 | "time"
24 | )
25 |
26 | func TestUnrmarshalInvalidMethod(t *testing.T) {
27 | jsonRequest := `{"method": "WHAT"}`
28 | _, err := unmarshalRequest([]byte(jsonRequest))
29 |
30 | if err.Error() != "invalid method: WHAT" {
31 | t.Errorf(`err.Error() = %v; want "invalid method: WHAT"`, err.Error())
32 | }
33 | }
34 |
35 | func TestUnrmarshalValid(t *testing.T) {
36 | jsonRequest := `{"method": "GET", "url": "http://example.com", "timestamp": "2021-11-08T18:59:59.9Z"}`
37 | req, err := unmarshalRequest([]byte(jsonRequest))
38 |
39 | if err != nil {
40 | t.Errorf("err = %v; want nil", err)
41 | }
42 |
43 | if req.Method != "GET" {
44 | t.Errorf("req.Method = %v; want GET", req.Method)
45 | }
46 |
47 | if req.Url != "http://example.com" {
48 | t.Errorf("req.Url = %v; want http://example.com", req.Url)
49 | }
50 |
51 | expectedTime, err := time.Parse(time.RFC3339, "2021-11-08T18:59:59.9Z")
52 |
53 | if err != nil {
54 | panic(err)
55 | }
56 |
57 | if req.Timestamp != expectedTime {
58 | t.Errorf("req.Timestamp = %v; want %v", req.Timestamp, expectedTime)
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/tools/linkerdxripley/pkg/converter/converter.go:
--------------------------------------------------------------------------------
1 | package converter
2 |
3 | import (
4 | "fmt"
5 | "net/url"
6 | "time"
7 |
8 | ripley "github.com/loveholidays/ripley/pkg"
9 | "github.com/loveholidays/ripley/tools/linkerdxripley/pkg/linkerd"
10 | )
11 |
12 | type Converter struct{}
13 |
14 | func New() *Converter {
15 | return &Converter{}
16 | }
17 |
18 | func (c *Converter) ConvertToRipley(linkerd linkerd.Request, newHost string, upgradeHTTPS bool) (*ripley.Request, error) {
19 | timestamp, err := c.parseTimestamp(linkerd.Timestamp)
20 | if err != nil {
21 | return nil, fmt.Errorf("failed to parse timestamp %s: %w", linkerd.Timestamp, err)
22 | }
23 |
24 | targetURL, err := c.buildTargetURL(linkerd.URI, newHost, upgradeHTTPS)
25 | if err != nil {
26 | return nil, fmt.Errorf("failed to build target URL: %w", err)
27 | }
28 |
29 | headers := c.buildHeaders(linkerd)
30 |
31 | ripleyReq := &ripley.Request{
32 | Method: linkerd.Method,
33 | Url: targetURL,
34 | Timestamp: timestamp,
35 | Headers: headers,
36 | }
37 |
38 | return ripleyReq, nil
39 | }
40 |
41 | func (c *Converter) parseTimestamp(timestampStr string) (time.Time, error) {
42 | return time.Parse(time.RFC3339Nano, timestampStr)
43 | }
44 |
45 | func (c *Converter) buildTargetURL(originalURI, newHost string, upgradeHTTPS bool) (string, error) {
46 | parsedURL, err := url.Parse(originalURI)
47 | if err != nil {
48 | return "", fmt.Errorf("failed to parse URI %s: %w", originalURI, err)
49 | }
50 |
51 | if newHost != "" {
52 | parsedURL.Host = newHost
53 | }
54 |
55 | if upgradeHTTPS && parsedURL.Scheme == "http" {
56 | parsedURL.Scheme = "https"
57 | }
58 |
59 | return parsedURL.String(), nil
60 | }
61 |
62 | func (c *Converter) buildHeaders(linkerd linkerd.Request) map[string]string {
63 | headers := make(map[string]string)
64 |
65 | if linkerd.UserAgent != "" {
66 | headers["User-Agent"] = linkerd.UserAgent
67 | }
68 |
69 | return headers
70 | }
71 |
--------------------------------------------------------------------------------
/tools/linkerdxripley/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "bufio"
5 | "encoding/json"
6 | "flag"
7 | "fmt"
8 | "log"
9 | "os"
10 | "strings"
11 |
12 | "github.com/loveholidays/ripley/tools/linkerdxripley/pkg/converter"
13 | "github.com/loveholidays/ripley/tools/linkerdxripley/pkg/linkerd"
14 | )
15 |
16 | func main() {
17 | var (
18 | newHost = flag.String("host", "", "New host to replace the original host in URLs")
19 | https = flag.Bool("https", false, "Upgrade HTTP requests to HTTPS")
20 | help = flag.Bool("help", false, "Show usage information")
21 | )
22 | flag.Parse()
23 |
24 | if *help {
25 | fmt.Fprintf(os.Stderr, "linkerdxripley - Convert Linkerd JSONL format to Ripley format\n\n")
26 | fmt.Fprintf(os.Stderr, "Usage: linkerdxripley [options] < input.jsonl > output.jsonl\n\n")
27 | fmt.Fprintf(os.Stderr, "Options:\n")
28 | flag.PrintDefaults()
29 | fmt.Fprintf(os.Stderr, "\nExamples:\n")
30 | fmt.Fprintf(os.Stderr, " cat linkerd.jsonl | linkerdxripley -host localhost:8080 > ripley.jsonl\n")
31 | fmt.Fprintf(os.Stderr, " cat linkerd.jsonl | linkerdxripley -host localhost:8080 -https > ripley.jsonl\n\n")
32 | return
33 | }
34 |
35 | conv := converter.New()
36 | scanner := bufio.NewScanner(os.Stdin)
37 | encoder := json.NewEncoder(os.Stdout)
38 | encoder.SetEscapeHTML(false)
39 |
40 | for scanner.Scan() {
41 | line := scanner.Text()
42 | line = strings.TrimSpace(line)
43 | if line == "" {
44 | continue
45 | }
46 |
47 | var linkerdReq linkerd.Request
48 | if err := json.Unmarshal([]byte(line), &linkerdReq); err != nil {
49 | log.Printf("failed to parse line: %s, error: %v", line, err)
50 | continue
51 | }
52 |
53 | ripleyReq, err := conv.ConvertToRipley(linkerdReq, *newHost, *https)
54 | if err != nil {
55 | log.Printf("failed to convert request: %v", err)
56 | continue
57 | }
58 |
59 | if err := encoder.Encode(ripleyReq); err != nil {
60 | log.Printf("failed to encode ripley request: %v", err)
61 | continue
62 | }
63 | }
64 |
65 | if err := scanner.Err(); err != nil {
66 | log.Fatalf("error reading input: %v", err)
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/pkg/request.go:
--------------------------------------------------------------------------------
1 | /*
2 | ripley
3 | Copyright (C) 2021 loveholidays
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU General Public License as published by
7 | the Free Software Foundation, either version 3 of the License, or
8 | (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU General Public License for more details.
14 |
15 | You should have received a copy of the GNU General Public License
16 | along with this program. If not, see .
17 | */
18 |
19 | package ripley
20 |
21 | import (
22 | "bytes"
23 | "encoding/json"
24 | "fmt"
25 | "net/http"
26 | "time"
27 | )
28 |
29 | var (
30 | validMethods = [9]string{"GET", "HEAD", "POST", "PUT", "DELETE", "CONNECT", "OPTIONS", "TRACE", "PATCH"}
31 | )
32 |
33 | type Request struct {
34 | Method string `json:"method"`
35 | Url string `json:"url"`
36 | Body string `json:"body"`
37 | Timestamp time.Time `json:"timestamp"`
38 | Headers map[string]string `json:"headers"`
39 | }
40 |
41 | func (r *Request) httpRequest() (*http.Request, error) {
42 | req, err := http.NewRequest(r.Method, r.Url, bytes.NewReader([]byte(r.Body)))
43 |
44 | if err != nil {
45 | return nil, err
46 | }
47 |
48 | for k, v := range r.Headers {
49 | req.Header.Add(k, v)
50 | }
51 |
52 | if host := req.Header.Get("Host"); host != "" {
53 | req.Host = host
54 | }
55 |
56 | return req, nil
57 | }
58 |
59 | func unmarshalRequest(jsonRequest []byte) (*Request, error) {
60 | req := &Request{}
61 | err := json.Unmarshal(jsonRequest, &req)
62 |
63 | if err != nil {
64 | return req, err
65 | }
66 |
67 | // Validate
68 | if !validMethod(req.Method) {
69 | return req, fmt.Errorf("invalid method: %s", req.Method)
70 | }
71 |
72 | if req.Url == "" {
73 | return req, fmt.Errorf("missing required key: url")
74 | }
75 |
76 | if req.Timestamp.IsZero() {
77 | return req, fmt.Errorf("missing required key: timestamp")
78 | }
79 |
80 | return req, nil
81 | }
82 |
83 | func validMethod(requestMethod string) bool {
84 | for _, method := range validMethods {
85 | if requestMethod == method {
86 | return true
87 | }
88 | }
89 | return false
90 | }
91 |
--------------------------------------------------------------------------------
/.goreleaser.yaml:
--------------------------------------------------------------------------------
1 | version: 2
2 |
3 | release:
4 | mode: replace
5 |
6 | before:
7 | hooks:
8 | - go mod tidy
9 | builds:
10 | - env:
11 | - CGO_ENABLED=0
12 | goos:
13 | - linux
14 | - darwin
15 | archives:
16 | - name_template: >-
17 | {{- .ProjectName }}_
18 | {{- title .Os }}_
19 | {{- if eq .Arch "amd64" }}x86_64
20 | {{- else if eq .Arch "386" }}i386
21 | {{- else }}{{ .Arch }}{{ end }}
22 | {{- if .Arm }}v{{ .Arm }}{{ end -}}
23 | checksum:
24 | name_template: 'checksums.txt'
25 | snapshot:
26 | name_template: "{{ incpatch .Version }}-next"
27 | changelog:
28 | sort: asc
29 | filters:
30 | exclude:
31 | - '^docs:'
32 | - '^test:'
33 | brews:
34 | -
35 | name: ripley
36 | repository:
37 | owner: loveholidays
38 | name: homebrew-tap
39 | commit_author:
40 | name: loveholidays
41 | email: oss@loveholidays.com
42 | directory: Formula
43 | homepage: "https://github.com/loveholidays/ripley"
44 | description: "Replays HTTP traffic at multiples of the original rate"
45 | install: |
46 | bin.install "ripley"
47 | license: "GPL-3.0"
48 | dockers:
49 | - image_templates: ["loveholidays/{{ .ProjectName }}:{{ .Version }}-amd64"]
50 | goarch: amd64
51 | dockerfile: Dockerfile
52 | build_flag_templates:
53 | - --platform=linux/amd64
54 | - --label=org.opencontainers.image.title={{ .ProjectName }}
55 | - --label=org.opencontainers.image.description={{ .ProjectName }}
56 | - --label=org.opencontainers.image.source=https://github.com/loveholidays/ripley
57 | - --label=org.opencontainers.image.version={{ .Version }}
58 | - --label=org.opencontainers.image.revision={{ .FullCommit }}
59 | - --label=org.opencontainers.image.licenses=GPL-3.0
60 | - image_templates: [ "loveholidays/{{ .ProjectName }}:latest" ]
61 | goarch: amd64
62 | dockerfile: Dockerfile
63 | build_flag_templates:
64 | - --platform=linux/amd64
65 | - --label=org.opencontainers.image.title={{ .ProjectName }}
66 | - --label=org.opencontainers.image.description={{ .ProjectName }}
67 | - --label=org.opencontainers.image.source=https://github.com/loveholidays/ripley
68 | - --label=org.opencontainers.image.version={{ .Version }}
69 | - --label=org.opencontainers.image.revision={{ .FullCommit }}
70 | - --label=org.opencontainers.image.licenses=GPL-3.0
71 |
--------------------------------------------------------------------------------
/pkg/client.go:
--------------------------------------------------------------------------------
1 | /*
2 | ripley
3 | Copyright (C) 2021 loveholidays
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU General Public License as published by
7 | the Free Software Foundation, either version 3 of the License, or
8 | (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU General Public License for more details.
14 |
15 | You should have received a copy of the GNU General Public License
16 | along with this program. If not, see .
17 | */
18 |
19 | package ripley
20 |
21 | import (
22 | "io"
23 | "net/http"
24 | "time"
25 | )
26 |
27 | type Result struct {
28 | StatusCode int `json:"statusCode"`
29 | Latency time.Duration `json:"latency"`
30 | Request *Request `json:"Request"`
31 | ErrorMsg string `json:"error"`
32 | }
33 |
34 | func startClientWorkers(numWorkers int, requests <-chan *Request, results chan<- *Result, dryRun bool, timeout, connections, maxConnections int) {
35 | client := &http.Client{
36 | Timeout: time.Duration(timeout) * time.Second,
37 | CheckRedirect: func(req *http.Request, via []*http.Request) error {
38 | return http.ErrUseLastResponse
39 | },
40 | Transport: &http.Transport{
41 | MaxIdleConnsPerHost: connections,
42 | MaxConnsPerHost: maxConnections,
43 | },
44 | }
45 |
46 | for i := 0; i < numWorkers; i++ {
47 | go doHttpRequest(client, requests, results, dryRun)
48 | }
49 | }
50 |
51 | func doHttpRequest(client *http.Client, requests <-chan *Request, results chan<- *Result, dryRun bool) {
52 | for req := range requests {
53 | latencyStart := time.Now()
54 |
55 | if dryRun {
56 | sendResult(req, &http.Response{}, latencyStart, "", results)
57 | } else {
58 | executeRequest(client, req, latencyStart, results)
59 | }
60 | }
61 | }
62 |
63 | func executeRequest(client *http.Client, req *Request, latencyStart time.Time, results chan<- *Result) {
64 | httpReq, err := req.httpRequest()
65 | if err != nil {
66 | sendResult(req, &http.Response{}, latencyStart, err.Error(), results)
67 | return
68 | }
69 |
70 | resp, err := client.Do(httpReq)
71 | if err != nil {
72 | sendResult(req, &http.Response{}, latencyStart, err.Error(), results)
73 | return
74 | }
75 |
76 | _, err = io.ReadAll(resp.Body)
77 | if closeErr := resp.Body.Close(); closeErr != nil && err == nil {
78 | err = closeErr
79 | }
80 |
81 | if err != nil {
82 | sendResult(req, &http.Response{}, latencyStart, err.Error(), results)
83 | return
84 | }
85 |
86 | sendResult(req, resp, latencyStart, "", results)
87 | }
88 |
89 | func sendResult(req *Request, resp *http.Response, latencyStart time.Time, err string, results chan<- *Result) {
90 | latency := time.Since(latencyStart)
91 | results <- &Result{StatusCode: resp.StatusCode, Latency: latency, Request: req, ErrorMsg: err}
92 | }
93 |
--------------------------------------------------------------------------------
/CLAUDE.md:
--------------------------------------------------------------------------------
1 | # CLAUDE.md
2 |
3 | This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
4 |
5 | ## Development Commands
6 |
7 | ### Building and Testing
8 | - **Build**: `go build -o ripley main.go`
9 | - **Test**: `go test pkg/*.go`
10 | - **Run sample server**: `go run etc/dummyweb.go` (starts HTTP server on :8080)
11 |
12 | ### Running Ripley
13 | - **Basic usage**: `cat etc/requests.jsonl | ./ripley`
14 | - **With pacing**: `./ripley -pace "10s@1 10s@5 1h@10"`
15 | - **Dry run**: `./ripley -pace "30s@1" -dry-run`
16 | - **Silent output**: `./ripley -silent`
17 |
18 | ### Tools
19 | - **Linkerd converter**: `go run tools/linkerdxripley/main.go`
20 | - Convert Linkerd access logs to Ripley format
21 | - Usage: `cat linkerd.jsonl | go run tools/linkerdxripley/main.go -host localhost:8080 > ripley.jsonl`
22 |
23 | ### Release Process
24 | - Push a new tag to `main` branch to trigger GoReleaser
25 | - GoReleaser configuration in `.goreleaser.yaml`
26 |
27 | ## Architecture
28 |
29 | ### Core Components
30 |
31 | **Main Package Structure:**
32 | - `main.go`: CLI entry point with command-line flags
33 | - `pkg/replay.go`: Core replay orchestrator that coordinates the entire process
34 | - `pkg/request.go`: HTTP request structures and validation
35 | - `pkg/pace.go`: Rate pacing engine with support for multiple phases
36 | - `pkg/client.go`: HTTP client worker pool and request execution
37 |
38 | **Data Flow:**
39 | 1. JSONL requests read from STDIN via `bufio.Scanner`
40 | 2. `pacer` controls replay timing based on original timestamps and rate multipliers
41 | 3. Worker pool of HTTP clients (`numWorkers` goroutines) processes requests concurrently
42 | 4. Results streamed to STDOUT as JSONL
43 |
44 | **Key Concepts:**
45 | - **Phases**: Time-bounded periods with different rate multipliers (e.g., "10s@1 5m@10")
46 | - **Rate Pacing**: Maintains original traffic patterns while scaling by rate multipliers
47 | - **Request Format**: JSON with required fields: `url`, `method`, `timestamp`
48 | - **Worker Pool**: Configurable number of HTTP client workers for concurrent processing
49 |
50 | ### Tools Architecture
51 |
52 | **Linkerd Converter (`tools/linkerdxripley/`):**
53 | - Converts Linkerd JSONL access logs to Ripley request format
54 | - Supports URL rewriting and HTTP-to-HTTPS upgrade
55 | - Modular converter package with clean separation of concerns
56 |
57 | ### Configuration
58 |
59 | **HTTP Client Settings:**
60 | - Default timeout: 10 seconds
61 | - Default max idle connections per host: 10,000
62 | - Configurable max connections per host (unlimited by default)
63 | - Redirect handling: Uses last response (no follow)
64 |
65 | **Performance Tuning:**
66 | - Worker count defaults to `runtime.NumCPU() * 2`
67 | - Connection pooling optimized for high-throughput scenarios
68 | - Memory and CPU profiling support via command-line flags
69 |
70 | ## Input/Output Format
71 |
72 | **Request Format (JSONL):**
73 | ```json
74 | {
75 | "url": "http://localhost:8080/path",
76 | "method": "GET|POST|PUT|DELETE|etc",
77 | "timestamp": "2021-11-08T18:59:58.9Z",
78 | "headers": {"Accept": "text/plain"},
79 | "body": "{\"key\": \"value\"}"
80 | }
81 | ```
82 |
83 | **Result Format (JSONL):**
84 | ```json
85 | {
86 | "statusCode": 200,
87 | "latency": 3915447,
88 | "request": { ... },
89 | "error": "optional error message"
90 | }
91 | ```
92 |
93 | ## Development Notes
94 |
95 | - Go version requirement: 1.22+
96 | - Strict mode available for development (`-strict` flag causes panic on bad input)
97 | - Comprehensive validation for HTTP methods and required fields
98 | - Built-in statistics reporting with configurable intervals
--------------------------------------------------------------------------------
/tools/linkerdxripley/go.sum:
--------------------------------------------------------------------------------
1 | github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
2 | github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
3 | github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
4 | github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
5 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
6 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
7 | github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
8 | github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
9 | github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
10 | github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
11 | github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
12 | github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
13 | github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
14 | github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
15 | github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
16 | github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
17 | github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
18 | github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
19 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
20 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
21 | github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o=
22 | github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg=
23 | github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
24 | github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
25 | github.com/prometheus/common v0.66.1 h1:h5E0h5/Y8niHc5DlaLlWLArTQI7tMrsfQjHV+d9ZoGs=
26 | github.com/prometheus/common v0.66.1/go.mod h1:gcaUsgf3KfRSwHY4dIMXLPV0K/Wg1oZ8+SbZk/HH/dA=
27 | github.com/prometheus/procfs v0.16.1 h1:hZ15bTNuirocR6u0JZ6BAHHmwS1p8B4P6MRqxtzMyRg=
28 | github.com/prometheus/procfs v0.16.1/go.mod h1:teAbpZRB1iIAJYREa1LsoWUXykVXA1KlTmWl8x/U+Is=
29 | github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=
30 | github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=
31 | github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
32 | github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
33 | go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
34 | go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
35 | go.yaml.in/yaml/v2 v2.4.2 h1:DzmwEr2rDGHl7lsFgAHxmNz/1NlQ7xLIrlN2h5d1eGI=
36 | go.yaml.in/yaml/v2 v2.4.2/go.mod h1:081UH+NErpNdqlCXm3TtEran0rJZGxAYx9hb/ELlsPU=
37 | golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI=
38 | golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
39 | google.golang.org/protobuf v1.36.8 h1:xHScyCOEuuwZEc6UtSOvPbAT4zRh0xcNRYekJwfqyMc=
40 | google.golang.org/protobuf v1.36.8/go.mod h1:fuxRtAxBytpl4zzqUh6/eyUujkJdNiuEkXntxiD/uRU=
41 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
42 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
43 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
44 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
45 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
46 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
2 | github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
3 | github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
4 | github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
5 | github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
6 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
7 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
8 | github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
9 | github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
10 | github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
11 | github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
12 | github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
13 | github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
14 | github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
15 | github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
16 | github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
17 | github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
18 | github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
19 | github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
20 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
21 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
22 | github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o=
23 | github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg=
24 | github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
25 | github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
26 | github.com/prometheus/common v0.66.1 h1:h5E0h5/Y8niHc5DlaLlWLArTQI7tMrsfQjHV+d9ZoGs=
27 | github.com/prometheus/common v0.66.1/go.mod h1:gcaUsgf3KfRSwHY4dIMXLPV0K/Wg1oZ8+SbZk/HH/dA=
28 | github.com/prometheus/procfs v0.16.1 h1:hZ15bTNuirocR6u0JZ6BAHHmwS1p8B4P6MRqxtzMyRg=
29 | github.com/prometheus/procfs v0.16.1/go.mod h1:teAbpZRB1iIAJYREa1LsoWUXykVXA1KlTmWl8x/U+Is=
30 | github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=
31 | github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=
32 | github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
33 | github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
34 | go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
35 | go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
36 | go.yaml.in/yaml/v2 v2.4.2 h1:DzmwEr2rDGHl7lsFgAHxmNz/1NlQ7xLIrlN2h5d1eGI=
37 | go.yaml.in/yaml/v2 v2.4.2/go.mod h1:081UH+NErpNdqlCXm3TtEran0rJZGxAYx9hb/ELlsPU=
38 | golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI=
39 | golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
40 | google.golang.org/protobuf v1.36.8 h1:xHScyCOEuuwZEc6UtSOvPbAT4zRh0xcNRYekJwfqyMc=
41 | google.golang.org/protobuf v1.36.8/go.mod h1:fuxRtAxBytpl4zzqUh6/eyUujkJdNiuEkXntxiD/uRU=
42 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
43 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
44 | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
45 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
46 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
47 |
--------------------------------------------------------------------------------
/pkg/pace_test.go:
--------------------------------------------------------------------------------
1 | /*
2 | ripley
3 | Copyright (C) 2021 loveholidays
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU General Public License as published by
7 | the Free Software Foundation, either version 3 of the License, or
8 | (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU General Public License for more details.
14 |
15 | You should have received a copy of the GNU General Public License
16 | along with this program. If not, see .
17 | */
18 |
19 | package ripley
20 |
21 | import (
22 | "math"
23 | "testing"
24 | "time"
25 | )
26 |
27 | func TestSimpleParsePhases(t *testing.T) {
28 | phases, err := parsePhases("5m@2.5")
29 |
30 | if err != nil {
31 | t.Fatalf("Unexpected error: %v", err)
32 | }
33 |
34 | if len(phases) != 1 {
35 | t.Errorf("len(phases) = %v; want 1", len(phases))
36 | }
37 |
38 | // 5 minutes in nanoseconds
39 | if phases[0].duration != 5*time.Minute {
40 | t.Errorf("phases[0].duration = %v; want 5 minutes", phases[0].duration)
41 | }
42 |
43 | if phases[0].rate != 2.5 {
44 | t.Errorf("phases[0].rate = %v; want 2.5", phases[0].rate)
45 | }
46 | }
47 |
48 | func TestParseManyPhases(t *testing.T) {
49 | actualPhases, err := parsePhases("5m@2.5 20m@5 1h30m@10")
50 |
51 | if err != nil {
52 | t.Fatalf("Unexpected error: %v", err)
53 | }
54 |
55 | expectedPhases := []*phase{
56 | {5 * time.Minute, 2.5},
57 | {20 * time.Minute, 5.0},
58 | {time.Hour + 30*time.Minute, 10.0}}
59 |
60 | if len(actualPhases) != len(expectedPhases) {
61 | t.Errorf("len(actualPhases) = %v; want 3", len(expectedPhases))
62 | }
63 |
64 | for i, expectedPhase := range expectedPhases {
65 | if actualPhases[i].duration != expectedPhase.duration {
66 | t.Errorf("actualPhases[i].duration = %v; want %v",
67 | actualPhases[i].duration, expectedPhase.duration)
68 | }
69 |
70 | if actualPhases[i].rate != expectedPhase.rate {
71 | t.Errorf("actualPhases[i].rate = %v; want %v",
72 | actualPhases[i].rate, expectedPhase.rate)
73 | }
74 | }
75 | }
76 |
77 | func TestWaitDuration(t *testing.T) {
78 | pacer, err := newPacer("30s@1")
79 |
80 | if err != nil {
81 | t.Fatalf("Unexpected error: %v", err)
82 | }
83 |
84 | now := time.Now()
85 | duration := pacer.waitDuration(now)
86 |
87 | if duration > 0 {
88 | t.Errorf("duration = %v; want 0 or negative", duration)
89 | }
90 |
91 | now = now.Add(2 * time.Second)
92 | duration = pacer.waitDuration(now)
93 | expected := 2 * time.Second
94 |
95 | if !equalsWithinThreshold(duration, expected, 100*time.Microsecond) {
96 | t.Errorf("duration = %v; want %v", duration, expected)
97 | }
98 | }
99 |
100 | func TestWaitDuration10X(t *testing.T) {
101 | pacer, err := newPacer("30s@10")
102 |
103 | if err != nil {
104 | t.Fatalf("Unexpected error: %v", err)
105 | }
106 |
107 | now := time.Now()
108 | duration := pacer.waitDuration(now)
109 |
110 | if duration > 0 {
111 | t.Errorf("duration = %v; want 0 or negative", duration)
112 | }
113 |
114 | now = now.Add(1 * time.Second)
115 | duration = pacer.waitDuration(now)
116 | expected := time.Second / 10
117 |
118 | if !equalsWithinThreshold(duration, expected, 100*time.Microsecond) {
119 | t.Errorf("duration = %v; want %v", duration, expected)
120 | }
121 | }
122 |
123 | func TestPacerDoneOnLastPhaseElapsed(t *testing.T) {
124 | pacer, err := newPacer("30s@10")
125 |
126 | if err != nil {
127 | t.Fatalf("Unexpected error: %v", err)
128 | }
129 |
130 | if pacer.done {
131 | t.Errorf("pacer.done = %v; want false", pacer.done)
132 | }
133 |
134 | pacer.onPhaseElapsed()
135 |
136 | if !pacer.done {
137 | t.Errorf("pacer.done = %v; want true", pacer.done)
138 | }
139 | }
140 |
141 | func equalsWithinThreshold(d1, d2, threshold time.Duration) bool {
142 | return math.Abs(float64(d1-d2)) <= float64(threshold)
143 | }
144 |
--------------------------------------------------------------------------------
/pkg/replay.go:
--------------------------------------------------------------------------------
1 | /*
2 | ripley
3 | Copyright (C) 2021 loveholidays
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU General Public License as published by
7 | the Free Software Foundation, either version 3 of the License, or
8 | (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU General Public License for more details.
14 |
15 | You should have received a copy of the GNU General Public License
16 | along with this program. If not, see .
17 | */
18 |
19 | package ripley
20 |
21 | import (
22 | "bufio"
23 | "encoding/json"
24 | "fmt"
25 | "os"
26 | "sync"
27 | "time"
28 | )
29 |
30 | func Replay(phasesStr string, silent, dryRun bool, timeout int, strict bool, numWorkers, connections, maxConnections int, printStatsInterval time.Duration, metricsServerEnable bool, metricsServerAddr string) int {
31 | // Default exit code
32 | var exitCode = 0
33 | // Ensures we have handled all HTTP Request results before exiting
34 | var waitGroup sync.WaitGroup
35 | // Ensures result handler goroutine completes before closing results channel
36 | var resultHandlerWG sync.WaitGroup
37 |
38 | // Send requests for the HTTP client workers to pick up on this channel
39 | requests := make(chan *Request)
40 |
41 | // HTTP client workers will send their results on this channel
42 | results := make(chan *Result)
43 |
44 | // Initialize metrics recorder (no-op if disabled)
45 | metricsRecorder := NewMetricsRecorder(MetricsConfig{
46 | Enabled: metricsServerEnable,
47 | Address: metricsServerAddr,
48 | }, numWorkers)
49 | stopMonitoring := metricsRecorder.StartMonitoring(requests, results)
50 | defer stopMonitoring()
51 |
52 | // The pacer controls the rate of replay
53 | pacer, err := newPacer(phasesStr)
54 | pacer.ReportInterval = printStatsInterval
55 |
56 | if err != nil {
57 | panic(err)
58 | }
59 |
60 | // Read Request JSONL input from STDIN
61 | scanner := bufio.NewScanner(bufio.NewReaderSize(os.Stdin, 32*1024*1024))
62 |
63 | // Start HTTP client goroutine pool
64 | startClientWorkers(numWorkers, requests, results, dryRun, timeout, connections, maxConnections)
65 | pacer.start()
66 |
67 | // Goroutine to handle the HTTP client result
68 | resultHandlerWG.Add(1)
69 | go func() {
70 | defer resultHandlerWG.Done()
71 | for result := range results {
72 | waitGroup.Done()
73 |
74 | // If there's a panic elsewhere, this channel can return nil
75 | if result == nil {
76 | return
77 | }
78 |
79 | metricsRecorder.RecordRequest(result)
80 |
81 | if !silent {
82 | jsonResult, err := json.Marshal(result)
83 |
84 | if err != nil {
85 | panic(err)
86 | }
87 |
88 | fmt.Println(string(jsonResult))
89 | }
90 | }
91 | }()
92 |
93 | for scanner.Scan() {
94 | req, err := unmarshalRequest(scanner.Bytes())
95 | if err != nil {
96 | exitCode = 126
97 | result, _ := json.Marshal(Result{
98 | StatusCode: 0,
99 | Latency: 0,
100 | Request: req,
101 | ErrorMsg: fmt.Sprintf("%v", err),
102 | })
103 | fmt.Println(string(result))
104 |
105 | if strict {
106 | panic(err)
107 | }
108 | continue
109 | }
110 |
111 | if pacer.isDone() {
112 | break
113 | }
114 |
115 | // The pacer decides how long to wait between requests
116 | waitDuration := pacer.waitDuration(req.Timestamp)
117 | time.Sleep(waitDuration)
118 | waitGroup.Add(1)
119 | requests <- req
120 | }
121 |
122 | if scanner.Err() != nil {
123 | panic(scanner.Err())
124 | }
125 |
126 | // Close requests channel to signal worker goroutines to stop
127 | close(requests)
128 |
129 | // Wait for all HTTP requests to complete
130 | waitGroup.Wait()
131 |
132 | // Close results channel to signal result handler to stop
133 | close(results)
134 |
135 | // Wait for result handler to finish processing all results
136 | resultHandlerWG.Wait()
137 |
138 | return exitCode
139 | }
140 |
--------------------------------------------------------------------------------
/main.go:
--------------------------------------------------------------------------------
1 | /*
2 | ripley
3 | Copyright (C) 2021 loveholidays
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU General Public License as published by
7 | the Free Software Foundation, either version 3 of the License, or
8 | (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU General Public License for more details.
14 |
15 | You should have received a copy of the GNU General Public License
16 | along with this program. If not, see .
17 | */
18 |
19 | package main
20 |
21 | import (
22 | "flag"
23 | "os"
24 | "runtime"
25 | "runtime/pprof"
26 |
27 | ripley "github.com/loveholidays/ripley/pkg"
28 | )
29 |
30 | func main() {
31 | exitCode := 0
32 |
33 | paceStr := flag.String("pace", "10s@1", `[duration]@[rate], e.g. "1m@1 30s@1.5 1h@2"`)
34 | silent := flag.Bool("silent", false, "Suppress output")
35 | dryRun := flag.Bool("dry-run", false, "Consume input but do not send HTTP requests to targets")
36 | timeout := flag.Int("timeout", 10, "HTTP client timeout in seconds")
37 | connections := flag.Int("connections", 10000, "Max open idle connections per target host")
38 | maxConnections := flag.Int("max-connections", 0, "Max connections per target host (default unlimited)")
39 | strict := flag.Bool("strict", false, "Panic on bad input")
40 | memprofile := flag.String("memprofile", "", "Write memory profile to `file` before exit")
41 | cpuprofile := flag.String("cpuprofile", "", "Write cpu profile to `file` before exit")
42 | numWorkers := flag.Int("workers", runtime.NumCPU()*2, "Number of client workers to use")
43 | metricsServerEnable := flag.Bool("metricsServerEnable", false, "Enable Prometheus metrics server on /metrics endpoint")
44 | metricsServerAddr := flag.String("metricsServerAddr", "0.0.0.0:8081", "Metrics server listen address")
45 | printStatsInterval := flag.Duration("print-stats", 0, `Statistics report interval, e.g., "1m"
46 |
47 | Each report line is printed to stderr with the following fields in logfmt format:
48 |
49 | report_time
50 | The calculated wall time for when this line should be printed in RFC3339 format.
51 |
52 | skew_seconds
53 | Difference between "report_time" and current time in seconds. When the absolute
54 | value of this is higher than about 100ms, it shows that ripley cannot generate
55 | enough load. Consider increasing workers, max connections, and/or CPU and IO requests.
56 |
57 | last_request_time
58 | Original request time of the last request in RFC3339 format.
59 |
60 | rate
61 | Current rate of playback as specified in "pace" flag.
62 |
63 | expected_rps
64 | Expected requests per second since the last report. This will differ from the
65 | actual requests per second if the system is unable to drive that many requests.
66 | If that is the case, consider increasing workers, max connections, and/or
67 | CPU and IO requests.
68 |
69 | When 0 (default) or negative, reporting is switched off.
70 | `)
71 |
72 | flag.Parse()
73 |
74 | if *cpuprofile != "" {
75 | f, err := os.Create(*cpuprofile)
76 |
77 | if err != nil {
78 | panic(err)
79 | }
80 |
81 | defer func() {
82 | if err := f.Close(); err != nil {
83 | panic(err)
84 | }
85 | }()
86 |
87 | if err := pprof.StartCPUProfile(f); err != nil {
88 | panic(err)
89 | }
90 |
91 | defer pprof.StopCPUProfile()
92 | }
93 |
94 | exitCode = ripley.Replay(*paceStr, *silent, *dryRun, *timeout, *strict, *numWorkers, *connections, *maxConnections, *printStatsInterval, *metricsServerEnable, *metricsServerAddr)
95 |
96 | if *memprofile != "" {
97 | f, err := os.Create(*memprofile)
98 |
99 | if err != nil {
100 | panic(err)
101 | }
102 |
103 | defer func() {
104 | if err := f.Close(); err != nil {
105 | panic(err)
106 | }
107 | }()
108 | runtime.GC()
109 |
110 | if err := pprof.WriteHeapProfile(f); err != nil {
111 | panic(err)
112 | }
113 | }
114 |
115 | os.Exit(exitCode)
116 | }
117 |
--------------------------------------------------------------------------------
/pkg/pace.go:
--------------------------------------------------------------------------------
1 | /*
2 | ripley
3 | Copyright (C) 2021 loveholidays
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU General Public License as published by
7 | the Free Software Foundation, either version 3 of the License, or
8 | (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU General Public License for more details.
14 |
15 | You should have received a copy of the GNU General Public License
16 | along with this program. If not, see .
17 | */
18 |
19 | package ripley
20 |
21 | import (
22 | "fmt"
23 | "os"
24 | "strconv"
25 | "strings"
26 | "sync"
27 | "time"
28 | )
29 |
30 | type pacer struct {
31 | ReportInterval time.Duration
32 | mu sync.RWMutex // protects all fields below
33 | phases []*phase
34 | lastRequestTime time.Time // last Request that we already replayed in "log time"
35 | lastRequestWallTime time.Time // last Request that we already replayed in "wall time"
36 | phaseStartRequestTime time.Time
37 | phaseStartWallTime time.Time
38 | done bool
39 | requestCounter int
40 | nextReport time.Time
41 | }
42 |
43 | type phase struct {
44 | duration time.Duration
45 | rate float64
46 | }
47 |
48 | func newPacer(phasesStr string) (*pacer, error) {
49 | phases, err := parsePhases(phasesStr)
50 |
51 | if err != nil {
52 | return nil, err
53 | }
54 |
55 | return &pacer{phases: phases}, nil
56 | }
57 |
58 | func (p *pacer) start() {
59 | p.mu.Lock()
60 | defer p.mu.Unlock()
61 |
62 | // Run a timer for the first phase's duration
63 | if len(p.phases) > 0 {
64 | time.AfterFunc(p.phases[0].duration, p.onPhaseElapsed)
65 | }
66 | if p.ReportInterval > 0 {
67 | p.nextReport = time.Now().Add(p.ReportInterval)
68 | }
69 | }
70 |
71 | func (p *pacer) onPhaseElapsed() {
72 | p.mu.Lock()
73 | defer p.mu.Unlock()
74 |
75 | // Pop phase
76 | if len(p.phases) > 0 {
77 | p.phases = p.phases[1:]
78 | }
79 | p.phaseStartRequestTime = p.lastRequestTime
80 | p.phaseStartWallTime = p.lastRequestWallTime
81 |
82 | if len(p.phases) == 0 {
83 | p.done = true
84 | } else {
85 | // Create a timer with next phase
86 | time.AfterFunc(p.phases[0].duration, p.onPhaseElapsed)
87 | }
88 | }
89 |
90 | func (p *pacer) waitDuration(t time.Time) time.Duration {
91 | p.mu.Lock()
92 | defer p.mu.Unlock()
93 |
94 | now := time.Now()
95 |
96 | if p.lastRequestTime.IsZero() {
97 | p.lastRequestTime = t
98 | p.lastRequestWallTime = now
99 | p.phaseStartRequestTime = p.lastRequestTime
100 | p.phaseStartWallTime = p.lastRequestWallTime
101 | }
102 |
103 | // Check if we have any phases left
104 | if len(p.phases) == 0 {
105 | return 0
106 | }
107 |
108 | originalDurationFromPhaseStart := t.Sub(p.phaseStartRequestTime)
109 | expectedDurationFromPhaseStart := time.Duration(float64(originalDurationFromPhaseStart) / p.phases[0].rate)
110 | expectedWallTime := p.phaseStartWallTime.Add(expectedDurationFromPhaseStart)
111 |
112 | p.reportStats(now, expectedWallTime)
113 |
114 | duration := expectedWallTime.Sub(now)
115 | p.lastRequestTime = t
116 | p.lastRequestWallTime = expectedWallTime
117 | return duration
118 | }
119 |
120 | func (p *pacer) isDone() bool {
121 | p.mu.RLock()
122 | defer p.mu.RUnlock()
123 | return p.done
124 | }
125 |
126 | func (p *pacer) reportStats(now, expectedWallTime time.Time) {
127 | if p.ReportInterval <= 0 {
128 | return
129 | }
130 |
131 | // Get current rate safely
132 | var currentRate = 1.0
133 | if len(p.phases) > 0 {
134 | currentRate = p.phases[0].rate
135 | }
136 |
137 | for p.nextReport.Before(expectedWallTime) {
138 | fmt.Fprintf(os.Stderr, "report_time=%s skew_seconds=%f last_request_time=%s rate=%f expected_rps=%d\n",
139 | p.nextReport.Format(time.RFC3339),
140 | now.Sub(p.nextReport).Seconds(),
141 | p.lastRequestTime.Format(time.RFC3339),
142 | currentRate,
143 | p.requestCounter/int(p.ReportInterval.Seconds()))
144 | p.nextReport = p.nextReport.Add(p.ReportInterval)
145 | p.requestCounter = 0
146 | }
147 | p.requestCounter++
148 | }
149 |
150 | // Format is [duration]@[rate] [duration]@[rate]..."
151 | // e.g. "5s@1 10m@2"
152 | func parsePhases(phasesStr string) ([]*phase, error) {
153 | var phases []*phase
154 |
155 | for _, durationAtRate := range strings.Split(phasesStr, " ") {
156 | tokens := strings.Split(durationAtRate, "@")
157 |
158 | duration, err := time.ParseDuration(tokens[0])
159 |
160 | if err != nil {
161 | return nil, err
162 | }
163 |
164 | rate, err := strconv.ParseFloat(tokens[1], 64)
165 |
166 | if err != nil {
167 | return nil, err
168 | }
169 |
170 | phases = append(phases, &phase{duration, rate})
171 | }
172 |
173 | return phases, nil
174 | }
175 |
--------------------------------------------------------------------------------
/tools/linkerdxripley/main_test.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "bytes"
5 | "encoding/json"
6 | "os/exec"
7 | "strings"
8 | "testing"
9 | )
10 |
11 | func TestCLIIntegration(t *testing.T) {
12 | t.Run("basic conversion without host change", func(t *testing.T) {
13 | testBasicConversion(t)
14 | })
15 |
16 | t.Run("conversion with host change", func(t *testing.T) {
17 | testHostChangeConversion(t)
18 | })
19 |
20 | t.Run("multiple lines processing", func(t *testing.T) {
21 | testMultipleLineProcessing(t)
22 | })
23 | }
24 |
25 | func testBasicConversion(t *testing.T) {
26 | linkerdData := getSampleLinkerdData()[0]
27 | output := runCLICommand(t, []string{}, linkerdData)
28 |
29 | result := parseJSONOutput(t, output)
30 | assertFieldEquals(t, result, "method", "GET")
31 | assertFieldEquals(t, result, "url", "http://api-service.test.svc.cluster.local/api/v1/data?id=12345")
32 | assertFieldEquals(t, result, "timestamp", "2025-09-03T15:30:32.928995068Z")
33 | }
34 |
35 | func testHostChangeConversion(t *testing.T) {
36 | linkerdData := getSampleLinkerdData()[0]
37 | output := runCLICommand(t, []string{"-host", "localhost:8080"}, linkerdData)
38 |
39 | result := parseJSONOutput(t, output)
40 | assertFieldEquals(t, result, "url", "http://localhost:8080/api/v1/data?id=12345")
41 | }
42 |
43 | func testMultipleLineProcessing(t *testing.T) {
44 | linkerdLines := getSampleLinkerdData()
45 | linkerdData := strings.Join(linkerdLines, "\n")
46 | output := runCLICommand(t, []string{"-host", "staging.test.com:9000"}, linkerdData)
47 |
48 | lines := strings.Split(strings.TrimSpace(output), "\n")
49 | if len(lines) != 2 {
50 | t.Fatalf("expected 2 output lines, got %d", len(lines))
51 | }
52 |
53 | for i, line := range lines {
54 | result := parseJSONOutput(t, line)
55 | url := getStringField(t, result, "url", i+1)
56 | assertContains(t, url, "staging.test.com:9000", i+1)
57 | }
58 | }
59 |
60 | func getSampleLinkerdData() []string {
61 | return []string{
62 | `{"client.addr":"192.168.1.100:12345","client.id":"test-service.default.serviceaccount.identity.linkerd.cluster.local","host":"api-service.test.svc.cluster.local","method":"GET","processing_ns":"50000","request_bytes":"0","status":200,"timestamp":"2025-09-03T15:30:32.928995068Z","total_ns":"2500000","trace_id":"abc123","uri":"http://api-service.test.svc.cluster.local/api/v1/data?id=12345","user_agent":"TestClient/1.0","version":"HTTP/2.0"}`,
63 | `{"client.addr":"192.168.1.101:54321","client.id":"another-service.default.serviceaccount.identity.linkerd.cluster.local","host":"api-service.test.svc.cluster.local","method":"POST","processing_ns":"75000","request_bytes":"256","status":201,"timestamp":"2025-09-03T15:30:33.123456789Z","total_ns":"3000000","trace_id":"def456","uri":"http://api-service.test.svc.cluster.local/api/v1/create","user_agent":"TestClient/2.0","version":"HTTP/2.0"}`,
64 | }
65 | }
66 |
67 | func runCLICommand(t *testing.T, args []string, input string) string {
68 | cmdArgs := append([]string{"run", "main.go"}, args...)
69 | cmd := exec.Command("go", cmdArgs...)
70 | cmd.Dir = "."
71 | cmd.Stdin = strings.NewReader(input)
72 |
73 | var stdout, stderr bytes.Buffer
74 | cmd.Stdout = &stdout
75 | cmd.Stderr = &stderr
76 |
77 | err := cmd.Run()
78 | if err != nil {
79 | t.Fatalf("CLI command failed: %v\nstderr: %s", err, stderr.String())
80 | }
81 |
82 | return stdout.String()
83 | }
84 |
85 | func parseJSONOutput(t *testing.T, output string) map[string]interface{} {
86 | var result map[string]interface{}
87 | err := json.Unmarshal([]byte(strings.TrimSpace(output)), &result)
88 | if err != nil {
89 | t.Fatalf("failed to parse output JSON: %v", err)
90 | }
91 | return result
92 | }
93 |
94 | func assertFieldEquals(t *testing.T, result map[string]interface{}, field, expected string) {
95 | if result[field] != expected {
96 | t.Errorf("expected %s %s, got %v", field, expected, result[field])
97 | }
98 | }
99 |
100 | func getStringField(t *testing.T, result map[string]interface{}, field string, lineNum int) string {
101 | value, ok := result[field].(string)
102 | if !ok {
103 | t.Fatalf("%s is not a string in line %d", field, lineNum)
104 | }
105 | return value
106 | }
107 |
108 | func assertContains(t *testing.T, actual, expected string, lineNum int) {
109 | if !strings.Contains(actual, expected) {
110 | t.Errorf("expected %s in line %d, got %s", expected, lineNum, actual)
111 | }
112 | }
113 |
114 | func TestPipelineIntegration(t *testing.T) {
115 | linkerdData := getSampleLinkerdData()[0]
116 | output := runCLICommand(t, []string{"-host", "localhost:8080"}, linkerdData)
117 |
118 | ripleyReq := parseJSONOutput(t, output)
119 | verifyRequiredRipleyFields(t, ripleyReq)
120 | assertFieldEquals(t, ripleyReq, "url", "http://localhost:8080/api/v1/data?id=12345")
121 |
122 | t.Logf("Successfully converted Linkerd format to Ripley format:\n%s", output)
123 | }
124 |
125 | func verifyRequiredRipleyFields(t *testing.T, ripleyReq map[string]interface{}) {
126 | requiredFields := []string{"method", "url", "timestamp"}
127 | for _, field := range requiredFields {
128 | if _, exists := ripleyReq[field]; !exists {
129 | t.Errorf("missing required Ripley field: %s", field)
130 | }
131 | }
132 | }
133 |
--------------------------------------------------------------------------------
/tools/linkerdxripley/README.md:
--------------------------------------------------------------------------------
1 | # linkerdxripley
2 |
3 | A CLI tool to convert Linkerd JSONL format to Ripley format for HTTP traffic replay.
4 |
5 | ## Overview
6 |
7 | This tool reads Linkerd service mesh access logs in JSONL format from stdin and converts them to Ripley's expected format, allowing you to replay real production traffic patterns for load testing.
8 |
9 | ## Prerequisites
10 |
11 | ### Enable Linkerd Access Logging
12 |
13 | To collect access logs from Linkerd, you need to add this annotation to your pods:
14 |
15 | ```yaml
16 | apiVersion: apps/v1
17 | kind: Deployment
18 | metadata:
19 | name: your-app
20 | spec:
21 | template:
22 | metadata:
23 | annotations:
24 | config.linkerd.io/access-log: json
25 | spec:
26 | # ... rest of your pod spec
27 | ```
28 |
29 | This annotation tells Linkerd to start writing JSON-formatted access logs to stdout.
30 |
31 | ### Collecting Logs with Loki
32 |
33 | If you're using Loki for log aggregation, you can extract Linkerd logs using `logcli`:
34 |
35 | #### Install logcli
36 | ```bash
37 | brew install logcli
38 | ```
39 |
40 | #### Port Forward to Loki
41 | ```bash
42 | kubectl port-forward -n loki deployment/loki-query-frontend 3100:3100
43 | ```
44 |
45 | #### Query Linkerd Logs
46 | ```bash
47 | logcli --addr=http://localhost:3100 query \
48 | --from="2025-09-03T15:26:52Z" \
49 | --to="2025-09-03T16:34:32Z" \
50 | --forward \
51 | --output=raw \
52 | --limit=0 \
53 | '{app="your-app
54 | ", container="linkerd-proxy"} |= `"method":"GET"` != `"uri":"/healthz"` != `"uri":"/metrics"`' \
55 | > linkerd-logs.txt
56 | ```
57 |
58 | This query:
59 | - Filters for logs from the `linkerd-proxy` container
60 | - Includes only GET requests
61 | - Excludes health check and metrics endpoints
62 | - Outputs raw JSON format suitable for this tool
63 |
64 | ## Usage
65 |
66 | ### Basic conversion
67 | ```bash
68 | cat linkerd_logs.jsonl | linkerdxripley > ripley_requests.jsonl
69 | ```
70 |
71 | ### With host modification
72 | ```bash
73 | cat linkerd_logs.jsonl | linkerdxripley -host localhost:8080 > ripley_requests.jsonl
74 | ```
75 |
76 | ### With HTTPS upgrade
77 | ```bash
78 | cat linkerd_logs.jsonl | linkerdxripley -https > ripley_requests.jsonl
79 | ```
80 |
81 | ### Combined host modification and HTTPS upgrade
82 | ```bash
83 | cat linkerd_logs.jsonl | linkerdxripley -host localhost:8443 -https > ripley_requests.jsonl
84 | ```
85 |
86 | ### Full pipeline with Ripley
87 | ```bash
88 | cat linkerd_logs.jsonl | linkerdxripley -host staging.api.com:9000 -https | ripley -pace "10s@1 30s@5"
89 | ```
90 |
91 | ## Options
92 |
93 | - `-host string`: Replace the original host in URLs with a new host (optional)
94 | - `-https`: Upgrade HTTP requests to HTTPS (optional)
95 | - `-help`: Show usage information
96 |
97 | ## Input Format (Linkerd JSONL)
98 |
99 | ```json
100 | {
101 | "client.addr": "192.168.1.100:12345",
102 | "client.id": "test-service.default.serviceaccount.identity.linkerd.cluster.local",
103 | "host": "api-service.test.svc.cluster.local",
104 | "method": "GET",
105 | "processing_ns": "50000",
106 | "request_bytes": "0",
107 | "status": 200,
108 | "timestamp": "2025-09-03T15:30:32.928995068Z",
109 | "total_ns": "2500000",
110 | "trace_id": "abc123",
111 | "uri": "http://api-service.test.svc.cluster.local/api/v1/data?id=12345",
112 | "user_agent": "TestClient/1.0",
113 | "version": "HTTP/2.0"
114 | }
115 | ```
116 |
117 | ## Output Format (Ripley JSONL)
118 |
119 | ```json
120 | {
121 | "method": "GET",
122 | "url": "http://localhost:8080/api/v1/data?id=12345",
123 | "timestamp": "2025-09-03T15:30:32.928995068Z",
124 | "headers": {
125 | "User-Agent": "TestClient/1.0",
126 | "Host": "api-service.test.svc.cluster.local"
127 | }
128 | }
129 | ```
130 |
131 | ## Field Mapping
132 |
133 | | Linkerd Field | Ripley Field | Notes |
134 | |---------------|--------------|-------|
135 | | `method` | `method` | HTTP method (GET, POST, etc.) |
136 | | `uri` | `url` | Request URL, optionally with modified host |
137 | | `timestamp` | `timestamp` | RFC3339Nano timestamp |
138 | | `user_agent` | `headers["User-Agent"]` | If present |
139 | | `host` | `headers["Host"]` | Original host preserved in headers |
140 |
141 | ## Building
142 |
143 | ```bash
144 | go build -o linkerdxripley main.go
145 | ```
146 |
147 | ## Testing
148 |
149 | ```bash
150 | # Run unit tests
151 | go test ./pkg/converter/
152 |
153 | # Run integration tests
154 | go test .
155 |
156 | # Test with sample data
157 | cat testdata/linkerd_sample.jsonl | go run main.go -host localhost:8080
158 | ```
159 |
160 | ## Examples
161 |
162 | ### Complete Workflow: Loki to Ripley
163 |
164 | 1. **Extract logs from Loki:**
165 | ```bash
166 | # Use the pre-configured port forward to Loki
167 | kubectl port-forward -n loki deployment/loki-query-frontend 3100:3100
168 |
169 | # Query and save Linkerd logs (adjust app name and time range)
170 | logcli --addr=http://localhost:3100 query \
171 | --from="2025-09-03T15:26:52Z" \
172 | --to="2025-09-03T16:34:32Z" \
173 | --forward \
174 | --output=raw \
175 | --limit=0 \
176 | '{app="your-app", container="linkerd-proxy"} |= `"method":"GET"` != `"uri":"/healthz"` != `"uri":"/metrics"`' \
177 | > production-linkerd.jsonl
178 | ```
179 |
180 | 2. **Convert and replay for load testing:**
181 | ```bash
182 | # Test against local environment with HTTPS
183 | cat production-linkerd.jsonl | \
184 | linkerdxripley -host localhost:3000 -https | \
185 | ripley -pace "1m@0.1"
186 |
187 | # Test against staging with ramped load and HTTPS
188 | cat production-linkerd.jsonl | \
189 | linkerdxripley -host staging.myapi.com -https | \
190 | ripley -pace "30s@1 5m@2 10m@5"
191 | ```
192 |
193 | ### Alternative: Direct kubectl logs
194 | If not using Loki, get logs directly from kubectl:
195 | ```bash
196 | kubectl logs -n your-namespace deployment/your-app -c linkerd-proxy --since=1h | \
197 | grep -E '^{' | \
198 | linkerdxripley -host localhost:3000 | \
199 | ripley -pace "1m@0.1"
200 | ```
--------------------------------------------------------------------------------
/.github/workflows/ci.yaml:
--------------------------------------------------------------------------------
1 | name: CI
2 |
3 | on:
4 | push:
5 | branches: [main]
6 | pull_request:
7 | branches: [main]
8 |
9 | permissions:
10 | id-token: write
11 | contents: write
12 |
13 | jobs:
14 | test:
15 | name: Test
16 | runs-on: ubuntu-latest
17 | strategy:
18 | matrix:
19 | go-version: [1.23.x]
20 |
21 | steps:
22 | - name: Checkout code
23 | uses: actions/checkout@v4
24 |
25 | - name: Set up Go
26 | uses: actions/setup-go@v5
27 | with:
28 | go-version: ${{ matrix.go-version }}
29 |
30 | - name: Cache Go modules
31 | uses: actions/cache@v4
32 | with:
33 | path: |
34 | ~/.cache/go-build
35 | ~/go/pkg/mod
36 | key: ${{ runner.os }}-go-${{ matrix.go-version }}-${{ hashFiles('**/go.sum') }}
37 | restore-keys: |
38 | ${{ runner.os }}-go-${{ matrix.go-version }}-
39 |
40 | - name: Download dependencies
41 | run: go mod download
42 |
43 | - name: Verify dependencies
44 | run: go mod verify
45 |
46 | - name: Run tests
47 | run: go test -v -race ./...
48 |
49 | - name: Test linkerdxripley tool
50 | run: |
51 | cd tools/linkerdxripley
52 | go test -v -race ./...
53 |
54 | build:
55 | name: Binaries Build
56 | runs-on: ubuntu-latest
57 | needs: test
58 |
59 | steps:
60 | - name: Checkout code
61 | uses: actions/checkout@v4
62 |
63 | - name: Authenticate to Google Cloud
64 | id: gcp-auth
65 | uses: google-github-actions/auth@71f986410dfbc7added4569d411d040a91dc6935 # v2.1.8
66 | with:
67 | token_format: access_token
68 | service_account: gcr-sa-cicd@loveholidays-ci-cd.iam.gserviceaccount.com
69 | workload_identity_provider: projects/829253466767/locations/global/workloadIdentityPools/github-actions-idp/providers/github-actions-idp
70 |
71 | - name: Login to GCR
72 | uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
73 | with:
74 | registry: eu.gcr.io
75 | username: oauth2accesstoken
76 | password: ${{ steps.gcp-auth.outputs.access_token }}
77 |
78 | - name: "Set up Cloud SDK"
79 | uses: "google-github-actions/setup-gcloud@v2"
80 |
81 | - name: docker registry configure europe-docker.pkg.dev for gcloud
82 | run: gcloud auth configure-docker europe-docker.pkg.dev
83 |
84 | - name: Set up Go
85 | uses: actions/setup-go@v5
86 | with:
87 | go-version: 1.23.x
88 |
89 | - name: Cache Go modules
90 | uses: actions/cache@v4
91 | with:
92 | path: |
93 | ~/.cache/go-build
94 | ~/go/pkg/mod
95 | key: ${{ runner.os }}-go-1.23.x-${{ hashFiles('**/go.sum') }}
96 | restore-keys: |
97 | ${{ runner.os }}-go-1.23.x-
98 |
99 | - name: Build main binary
100 | run: go build -v -o ripley main.go
101 |
102 | - name: Build linkerdxripley tool
103 | run: |
104 | cd tools/linkerdxripley
105 | go build -v -o linkerdxripley main.go
106 |
107 | - name: Test binaries work
108 | run: |
109 | ./ripley --help
110 | ./tools/linkerdxripley/linkerdxripley --help
111 |
112 | - name: Upload build artifacts
113 | uses: actions/upload-artifact@v4
114 | with:
115 | name: binaries
116 | path: |
117 | ripley
118 | tools/linkerdxripley/linkerdxripley
119 |
120 | lint:
121 | name: Lint
122 | runs-on: ubuntu-latest
123 |
124 | steps:
125 | - name: Checkout code
126 | uses: actions/checkout@v4
127 |
128 | - name: Set up Go
129 | uses: actions/setup-go@v5
130 | with:
131 | go-version: 1.23.x
132 |
133 | - name: Run golangci-lint
134 | uses: golangci/golangci-lint-action@v6
135 | with:
136 | version: latest
137 | args: --timeout=5m
138 |
139 | docker:
140 | name: Docker Build
141 | runs-on: ubuntu-latest
142 | needs: [test, build]
143 |
144 | steps:
145 | - name: Checkout code
146 | uses: actions/checkout@v4
147 |
148 | - name: Authenticate to Google Cloud
149 | id: gcp-auth
150 | uses: google-github-actions/auth@71f986410dfbc7added4569d411d040a91dc6935 # v2.1.8
151 | with:
152 | token_format: access_token
153 | service_account: gcr-sa-cicd@loveholidays-ci-cd.iam.gserviceaccount.com
154 | workload_identity_provider: projects/829253466767/locations/global/workloadIdentityPools/github-actions-idp/providers/github-actions-idp
155 |
156 | - name: Login to GCR
157 | uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
158 | with:
159 | registry: eu.gcr.io
160 | username: oauth2accesstoken
161 | password: ${{ steps.gcp-auth.outputs.access_token }}
162 |
163 | - name: Download build artifacts
164 | uses: actions/download-artifact@v4
165 | with:
166 | name: binaries
167 | path: .
168 |
169 | - name: Make binaries executable
170 | run: chmod +x ripley tools/linkerdxripley/linkerdxripley
171 |
172 | - name: Set up Docker Buildx
173 | uses: docker/setup-buildx-action@v3
174 |
175 | - name: Build Docker image
176 | uses: docker/build-push-action@v5
177 | with:
178 | context: .
179 | file: ./Dockerfile
180 | push: true
181 | platforms: linux/amd64,linux/arm64
182 | tags: |
183 | eu.gcr.io/loveholidays-ci-cd/ripley:latest
184 | eu.gcr.io/loveholidays-ci-cd/ripley:${{ github.sha }}
185 | cache-from: type=gha
186 | cache-to: type=gha,mode=max
187 |
188 | - name: Test Docker image
189 | run: |
190 | docker run --rm eu.gcr.io/loveholidays-ci-cd/ripley:latest --help
191 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # ripley - replay HTTP
2 |
3 | Ripley replays HTTP traffic at multiples of the original rate. While similar tools usually generate load at a set rate, such as 100 requests per second, ripley uses request timestamps, for example those recorded in access logs, to more accurately represent real world load. It simulates traffic ramp up or down by specifying rate phases for each run. For example, you can replay HTTP requests at twice the original rate for ten minutes, then three times the original rate for five minutes, then ten times the original rate for an hour and so on. Ripley's original use case is load testing by replaying HTTP access logs from production applications.
4 |
5 | ## Install
6 |
7 | ```bash
8 | # go >= 1.17
9 | # Using `go get` to install binaries is deprecated.
10 | # The version suffix is mandatory.
11 | go install github.com/loveholidays/ripley@latest
12 |
13 | # go < 1.17
14 | go get github.com/loveholidays/ripley
15 | ```
16 |
17 | ### Homebrew
18 |
19 | ```bash
20 | brew install loveholidays/tap/ripley
21 | ```
22 |
23 | ### Docker
24 | ```bash
25 | docker pull loveholidays/ripley
26 | ```
27 |
28 | ### Linux
29 | Grab the latest OS/Arch compatible binary from our [Releases](https://github.com/loveholidays/ripley/releases) page.
30 |
31 | ### From source
32 | ```bash
33 | git clone git@github.com:loveholidays/ripley.git
34 | cd ripley
35 | go build -o ripley main.go
36 | ```
37 |
38 | #### Quickstart from source
39 | Run a web server to replay traffic against
40 |
41 | ```bash
42 | go run etc/dummyweb.go
43 | ```
44 |
45 | Loop 10 times over a set of HTTP requests at 1x rate for 10 seconds, then at 5x for 10 seconds, then at 10x for the remaining requests
46 |
47 | ```bash
48 | seq 10 | xargs -I{} cat etc/requests.jsonl | ./ripley -pace "10s@1 10s@5 1h@10"
49 | ```
50 |
51 | ## Replaying HTTP traffic
52 |
53 | Ripley reads a representation of HTTP requests in [JSON Lines format](https://jsonlines.org/) from `STDIN` and replays them at different rates in phases as specified by the `-pace` flag.
54 |
55 | An example ripley request:
56 |
57 | ```JSON
58 | {
59 | "url": "http://localhost:8080/",
60 | "method": "POST",
61 | "body": "{\"foo\": \"bar\"}",
62 | "headers": {
63 | "Accept": "text/plain"
64 | },
65 | "timestamp": "2021-11-08T18:59:58.9Z"
66 | }
67 | ```
68 |
69 | `url`, `method` and `timestamp` are required, `headers` and `body` are optional.
70 |
71 | `-pace` specifies rate phases in `[duration]@[rate]` format. For example, `10s@5 5m@10 1h30m@100` means replay traffic at 5x for 10 seconds, 10x for 5 minutes and 100x for one and a half hours. The run will stop either when ripley stops receiving requests from `STDIN` or when the last phase elapses, whichever happens first.
72 |
73 | Ripley writes request results as JSON Lines to `STDOUT`
74 |
75 | ```bash
76 | echo '{"url": "http://localhost:8080/", "method": "GET", "timestamp": "2021-11-08T18:59:50.9Z"}' | ./ripley | jq
77 | ```
78 |
79 | produces
80 |
81 | ```JSON
82 | {
83 | "statusCode": 200,
84 | "latency": 3915447,
85 | "request": {
86 | "method": "GET",
87 | "url": "http://localhost:8080/",
88 | "body": "",
89 | "timestamp": "2021-11-08T18:59:50.9Z",
90 | "headers": null
91 | }
92 | }
93 | ```
94 |
95 | Results output can be suppressed using the `-silent` flag.
96 |
97 | For an example of working with ripley's output to generate statistics, refer to https://gist.github.com/georgemalamidis-lh/39b4f4a6c9c82f6cc8b7370219e93cd2
98 |
99 | ```bash
100 | cat etc/requests.jsonl | ./ripley | go run ripley_stats.go | jq
101 | ```
102 |
103 | ```JSON
104 | {
105 | "totalRequests": 10,
106 | "statusCodes": {
107 | "200": 10
108 | },
109 | "latency": {
110 | "max": 2074819,
111 | "mean": 968998.6,
112 | "median": 843486,
113 | "min": 696708,
114 | "p95": 1548438.5,
115 | "p99": 1548438.5,
116 | "stdDev": 377913.54080112034
117 | }
118 | }
119 | ```
120 |
121 | It is possible to disable sending HTTP requests to the targets with the `-dry-run` flag:
122 |
123 | ```bash
124 | cat etc/requests.jsonl | ./ripley -pace "30s@1" -dry-run
125 | ```
126 |
127 | ## Converting Linkerd Access Logs
128 |
129 | The `linkerdxripley` tool converts [Linkerd](https://linkerd.io/) JSONL access logs into Ripley's request format, enabling you to replay production Linkerd traffic for load testing.
130 |
131 | ### Installation
132 |
133 | Build from source:
134 | ```bash
135 | cd tools/linkerdxripley
136 | go build -o linkerdxripley main.go
137 | ```
138 |
139 | Or install directly:
140 | ```bash
141 | go install github.com/loveholidays/ripley/tools/linkerdxripley@latest
142 | ```
143 |
144 | ### Usage
145 |
146 | Basic conversion:
147 | ```bash
148 | cat linkerd.jsonl | linkerdxripley > ripley.jsonl
149 | ```
150 |
151 | Convert with host replacement:
152 | ```bash
153 | cat linkerd.jsonl | linkerdxripley -host localhost:8080 > ripley.jsonl
154 | ```
155 |
156 | Convert with HTTPS upgrade:
157 | ```bash
158 | cat linkerd.jsonl | linkerdxripley -host localhost:8443 -https > ripley.jsonl
159 | ```
160 |
161 | Full pipeline (convert and replay):
162 | ```bash
163 | cat linkerd.jsonl | linkerdxripley -host localhost:8080 | ./ripley -pace "1m@2 5m@5"
164 | ```
165 |
166 | ### Input Format
167 |
168 | The tool expects Linkerd JSONL access logs with these fields:
169 |
170 | ```json
171 | {
172 | "client.addr": "192.168.1.100:12345",
173 | "client.id": "service.namespace.serviceaccount.identity.linkerd.cluster.local",
174 | "host": "api.example.com",
175 | "method": "GET",
176 | "processing_ns": "50000",
177 | "request_bytes": "256",
178 | "status": 200,
179 | "timestamp": "2025-09-03T15:30:32.928995068Z",
180 | "total_ns": "2500000",
181 | "trace_id": "abc123",
182 | "uri": "http://api.example.com/api/v1/data?id=123",
183 | "user_agent": "MyApp/1.0",
184 | "version": "HTTP/2.0"
185 | }
186 | ```
187 |
188 | Required fields: `method`, `timestamp`, `uri`
189 |
190 | ### Output Format
191 |
192 | Produces Ripley-compatible JSONL:
193 |
194 | ```json
195 | {
196 | "method": "GET",
197 | "url": "http://localhost:8080/api/v1/data?id=123",
198 | "body": "",
199 | "timestamp": "2025-09-03T15:30:32.928995068Z",
200 | "headers": {
201 | "User-Agent": "MyApp/1.0"
202 | }
203 | }
204 | ```
205 |
206 | ### Command Options
207 |
208 | - `-host ` - Replace the original host with a new target host
209 | - `-https` - Upgrade HTTP requests to HTTPS (useful for local testing with TLS)
210 | - `-help` - Show usage information
211 |
212 | ## Running the tests
213 |
214 | ```bash
215 | go test pkg/*.go
216 | ```
217 |
218 | ## Releasing new versions
219 | Push a new tag to `main` to trigger the GoReleaser process.
220 |
--------------------------------------------------------------------------------
/pkg/replay_integration_test.go:
--------------------------------------------------------------------------------
1 | /*
2 | ripley
3 | Copyright (C) 2021 loveholidays
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU General Public License as published by
7 | the Free Software Foundation, either version 3 of the License, or
8 | (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU General Public License for more details.
14 |
15 | You should have received a copy of the GNU General Public License
16 | along with this program. If not, see .
17 | */
18 |
19 | package ripley
20 |
21 | import (
22 | "bytes"
23 | "net/http"
24 | "net/http/httptest"
25 | "os"
26 | "sync"
27 | "sync/atomic"
28 | "testing"
29 | "time"
30 | )
31 |
32 | func TestReplayRaceConditionTermination(t *testing.T) {
33 | // Create a test server that responds slowly to increase chance of race condition
34 | var requestCount int64
35 | server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
36 | atomic.AddInt64(&requestCount, 1)
37 | // Add small delay to increase race condition likelihood
38 | time.Sleep(10 * time.Millisecond)
39 | w.WriteHeader(http.StatusOK)
40 | _, _ = w.Write([]byte("OK"))
41 | }))
42 | defer server.Close()
43 |
44 | // Create test requests using the test server URL
45 | testRequests := createTestRequests(server.URL, 50)
46 |
47 | // Save original stdin
48 | originalStdin := os.Stdin
49 |
50 | // Run multiple iterations to increase chance of reproducing the race condition
51 | for i := 0; i < 100; i++ {
52 | t.Run("iteration", func(t *testing.T) {
53 | // Reset request count
54 | atomic.StoreInt64(&requestCount, 0)
55 |
56 | // Create a pipe to simulate stdin
57 | r, w, err := os.Pipe()
58 | if err != nil {
59 | t.Fatalf("Failed to create pipe: %v", err)
60 | }
61 |
62 | // Replace stdin
63 | os.Stdin = r
64 |
65 | // Write test data to pipe in a goroutine
66 | go func() {
67 | defer func() { _ = w.Close() }()
68 | _, _ = w.Write([]byte(testRequests))
69 | }()
70 |
71 | // Capture stdout to suppress output during test
72 | originalStdout := os.Stdout
73 | _, captureWriter, _ := os.Pipe()
74 | os.Stdout = captureWriter
75 |
76 | // Run the replay function with a short phase duration to complete quickly
77 | // Use high worker count and connections to increase goroutine concurrency
78 | exitCode := Replay("100ms@10", true, false, 1, false, 20, 100, 0, 0, false, "")
79 |
80 | // Restore stdout
81 | os.Stdout = originalStdout
82 | _ = captureWriter.Close()
83 |
84 | // Restore stdin
85 | os.Stdin = originalStdin
86 | _ = r.Close()
87 |
88 | // Verify that the function completed successfully
89 | if exitCode != 0 {
90 | t.Errorf("Expected exit code 0, got %d", exitCode)
91 | }
92 |
93 | // Add a small delay to let any lingering goroutines finish
94 | time.Sleep(50 * time.Millisecond)
95 | })
96 | }
97 | }
98 |
99 | func TestReplayRaceConditionWithSlowServer(t *testing.T) {
100 | // Create a server that responds very slowly to maximize race condition exposure
101 | var wg sync.WaitGroup
102 | server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
103 | wg.Add(1)
104 | defer wg.Done()
105 | // Longer delay to ensure requests are still processing when Replay tries to exit
106 | time.Sleep(200 * time.Millisecond)
107 | w.WriteHeader(http.StatusOK)
108 | _, _ = w.Write([]byte("OK"))
109 | }))
110 | defer server.Close()
111 |
112 | testRequests := createTestRequests(server.URL, 10)
113 |
114 | // Save original stdin/stdout
115 | originalStdin := os.Stdin
116 | originalStdout := os.Stdout
117 |
118 | for i := 0; i < 20; i++ {
119 | t.Run("slow_server_iteration", func(t *testing.T) {
120 | // Create pipe for stdin
121 | r, w, err := os.Pipe()
122 | if err != nil {
123 | t.Fatalf("Failed to create pipe: %v", err)
124 | }
125 | defer func() { _ = r.Close() }()
126 |
127 | os.Stdin = r
128 |
129 | // Capture stdout
130 | _, captureWriter, _ := os.Pipe()
131 | os.Stdout = captureWriter
132 |
133 | // Write test data
134 | go func() {
135 | defer func() { _ = w.Close() }()
136 | _, _ = w.Write([]byte(testRequests))
137 | }()
138 |
139 | // Run with very short phase to trigger early completion attempt
140 | start := time.Now()
141 | exitCode := Replay("50ms@5", true, false, 1, false, 10, 50, 0, 0, false, "")
142 | duration := time.Since(start)
143 |
144 | // Restore streams
145 | os.Stdout = originalStdout
146 | os.Stdin = originalStdin
147 | _ = captureWriter.Close()
148 |
149 | if exitCode != 0 {
150 | t.Errorf("Expected exit code 0, got %d", exitCode)
151 | }
152 |
153 | // The test should complete in reasonable time despite slow server
154 | // If it hangs due to race condition, this will fail
155 | if duration > 5*time.Second {
156 | t.Errorf("Replay took too long (%v), possible race condition causing hang", duration)
157 | }
158 | })
159 | }
160 |
161 | // Wait for any remaining server requests to complete
162 | wg.Wait()
163 | }
164 |
165 | func TestReplayRaceConditionStressTest(t *testing.T) {
166 | // Stress test with many concurrent requests and workers
167 | var requestCounter int64
168 | server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
169 | // Random delay to simulate real-world variance
170 | counter := atomic.AddInt64(&requestCounter, 1)
171 | delay := time.Duration(10+counter%50) * time.Millisecond
172 | time.Sleep(delay)
173 | w.WriteHeader(http.StatusOK)
174 | _, _ = w.Write([]byte("OK"))
175 | }))
176 | defer server.Close()
177 |
178 | // Generate many requests
179 | testRequests := createTestRequests(server.URL, 200)
180 |
181 | originalStdin := os.Stdin
182 | originalStdout := os.Stdout
183 |
184 | // Run stress test iterations
185 | for i := 0; i < 50; i++ {
186 | t.Run("stress_iteration", func(t *testing.T) {
187 | r, w, err := os.Pipe()
188 | if err != nil {
189 | t.Fatalf("Failed to create pipe: %v", err)
190 | }
191 | defer func() { _ = r.Close() }()
192 |
193 | os.Stdin = r
194 | _, captureWriter, _ := os.Pipe()
195 | os.Stdout = captureWriter
196 |
197 | go func() {
198 | defer func() { _ = w.Close() }()
199 | _, _ = w.Write([]byte(testRequests))
200 | }()
201 |
202 | // High concurrency settings to maximize race condition potential
203 | start := time.Now()
204 | exitCode := Replay("200ms@20", true, false, 2, false, 50, 200, 0, 0, false, "")
205 | duration := time.Since(start)
206 |
207 | os.Stdout = originalStdout
208 | os.Stdin = originalStdin
209 | _ = captureWriter.Close()
210 |
211 | if exitCode != 0 {
212 | t.Errorf("Expected exit code 0, got %d", exitCode)
213 | }
214 |
215 | // Should not hang indefinitely
216 | if duration > 10*time.Second {
217 | t.Errorf("Replay took too long (%v), possible deadlock", duration)
218 | }
219 | })
220 | }
221 | }
222 |
223 | // Helper function to create test request data
224 | func createTestRequests(serverURL string, count int) string {
225 | var buffer bytes.Buffer
226 | baseTime := time.Now()
227 |
228 | for i := 0; i < count; i++ {
229 | timestamp := baseTime.Add(time.Duration(i) * 100 * time.Millisecond)
230 | buffer.WriteString(`{"url": "`)
231 | buffer.WriteString(serverURL)
232 | buffer.WriteString(`", "method": "GET", "timestamp": "`)
233 | buffer.WriteString(timestamp.Format(time.RFC3339Nano))
234 | buffer.WriteString(`"}`)
235 | buffer.WriteString("\n")
236 | }
237 |
238 | return buffer.String()
239 | }
240 |
--------------------------------------------------------------------------------
/pkg/metrics.go:
--------------------------------------------------------------------------------
1 | /*
2 | ripley
3 | Copyright (C) 2021 loveholidays
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU General Public License as published by
7 | the Free Software Foundation, either version 3 of the License, or
8 | (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU General Public License for more details.
14 |
15 | You should have received a copy of the GNU General Public License
16 | along with this program. If not, see .
17 | */
18 |
19 | package ripley
20 |
21 | import (
22 | "log"
23 | "net/http"
24 | "net/url"
25 | "time"
26 |
27 | "github.com/prometheus/client_golang/prometheus"
28 | "github.com/prometheus/client_golang/prometheus/promhttp"
29 | )
30 |
31 | var (
32 | // Request duration histogram
33 | // Note: Uses host (not full URL) to prevent high cardinality issues
34 | requestDuration = prometheus.NewHistogramVec(
35 | prometheus.HistogramOpts{
36 | Name: "ripley_request_duration_seconds",
37 | Help: "HTTP request latencies in seconds by target host",
38 | Buckets: prometheus.DefBuckets,
39 | },
40 | []string{"host"},
41 | )
42 |
43 | // Response status code counter
44 | // Note: Uses host (not full URL) to prevent high cardinality issues
45 | responseStatus = prometheus.NewCounterVec(
46 | prometheus.CounterOpts{
47 | Name: "ripley_response_status_total",
48 | Help: "Total number of HTTP responses by status code and target host",
49 | },
50 | []string{"status_code", "host"},
51 | )
52 |
53 | // Total requests counter
54 | requestsTotal = prometheus.NewCounter(
55 | prometheus.CounterOpts{
56 | Name: "ripley_requests_total",
57 | Help: "Total number of HTTP requests sent",
58 | },
59 | )
60 |
61 | // Errors counter
62 | // Note: Uses host (not full URL) to prevent high cardinality issues
63 | errorsTotal = prometheus.NewCounterVec(
64 | prometheus.CounterOpts{
65 | Name: "ripley_errors_total",
66 | Help: "Total number of errors by target host",
67 | },
68 | []string{"host"},
69 | )
70 |
71 | // Pacer phase gauge
72 | pacerPhase = prometheus.NewGaugeVec(
73 | prometheus.GaugeOpts{
74 | Name: "ripley_pacer_phase",
75 | Help: "Current pacer phase rate multiplier",
76 | },
77 | []string{"phase"},
78 | )
79 |
80 | // Worker pool size gauge
81 | workerPoolSize = prometheus.NewGauge(
82 | prometheus.GaugeOpts{
83 | Name: "ripley_worker_pool_size",
84 | Help: "Number of worker goroutines",
85 | },
86 | )
87 |
88 | // Request queue size gauge
89 | requestQueueSize = prometheus.NewGauge(
90 | prometheus.GaugeOpts{
91 | Name: "ripley_request_queue_size",
92 | Help: "Current size of the request queue",
93 | },
94 | )
95 |
96 | // Result queue size gauge
97 | resultQueueSize = prometheus.NewGauge(
98 | prometheus.GaugeOpts{
99 | Name: "ripley_result_queue_size",
100 | Help: "Current size of the result queue",
101 | },
102 | )
103 | )
104 |
105 | // MetricsConfig holds metrics server configuration
106 | type MetricsConfig struct {
107 | Enabled bool
108 | Address string
109 | }
110 |
111 | // MetricsRecorder interface for recording metrics
112 | type MetricsRecorder interface {
113 | RecordRequest(result *Result)
114 | StartMonitoring(requests chan *Request, results chan *Result) func()
115 | }
116 |
117 | // prometheusRecorder implements MetricsRecorder with actual Prometheus metrics
118 | type prometheusRecorder struct {
119 | stopMonitoring chan bool
120 | }
121 |
122 | // noopRecorder implements MetricsRecorder with no-op implementations
123 | type noopRecorder struct{}
124 |
125 | // NewMetricsRecorder creates a metrics recorder based on configuration
126 | func NewMetricsRecorder(config MetricsConfig, numWorkers int) MetricsRecorder {
127 | if config.Enabled {
128 | errChan := StartMetricsServer(config)
129 |
130 | // Monitor for server errors in background
131 | go func() {
132 | if err := <-errChan; err != nil {
133 | log.Printf("WARNING: Metrics server unavailable, continuing without metrics: %v", err)
134 | }
135 | }()
136 |
137 | SetWorkerPoolSize(numWorkers)
138 | return &prometheusRecorder{stopMonitoring: make(chan bool)}
139 | }
140 | return &noopRecorder{}
141 | }
142 |
143 | func (p *prometheusRecorder) RecordRequest(result *Result) {
144 | RecordRequest(result)
145 | }
146 |
147 | func (p *prometheusRecorder) StartMonitoring(requests chan *Request, results chan *Result) func() {
148 | go MonitorQueueSizes(requests, results, p.stopMonitoring)
149 | return func() {
150 | p.stopMonitoring <- true
151 | }
152 | }
153 |
154 | func (n *noopRecorder) RecordRequest(result *Result) {}
155 |
156 | func (n *noopRecorder) StartMonitoring(requests chan *Request, results chan *Result) func() {
157 | return func() {} // Return no-op cleanup function
158 | }
159 |
160 | func init() {
161 | // Register metrics with Prometheus's default registry
162 | prometheus.MustRegister(requestDuration)
163 | prometheus.MustRegister(responseStatus)
164 | prometheus.MustRegister(requestsTotal)
165 | prometheus.MustRegister(errorsTotal)
166 | prometheus.MustRegister(pacerPhase)
167 | prometheus.MustRegister(workerPoolSize)
168 | prometheus.MustRegister(requestQueueSize)
169 | prometheus.MustRegister(resultQueueSize)
170 | }
171 |
172 | // StartMetricsServer starts the Prometheus metrics HTTP server
173 | // Returns an error channel that will receive any server startup or runtime errors
174 | func StartMetricsServer(config MetricsConfig) <-chan error {
175 | errChan := make(chan error, 1)
176 |
177 | if !config.Enabled {
178 | close(errChan)
179 | return errChan
180 | }
181 |
182 | mux := http.NewServeMux()
183 | mux.Handle("/metrics", promhttp.Handler())
184 |
185 | server := &http.Server{
186 | Addr: config.Address,
187 | Handler: mux,
188 | }
189 |
190 | go func() {
191 | log.Printf("Starting metrics server on %s", config.Address)
192 | if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
193 | log.Printf("Metrics server failed: %v", err)
194 | errChan <- err
195 | }
196 | close(errChan)
197 | }()
198 |
199 | return errChan
200 | }
201 |
202 | // extractHost extracts the host from a URL to prevent high cardinality issues.
203 | // Falls back to "unknown" if parsing fails or host is empty.
204 | func extractHost(urlStr string) string {
205 | parsedURL, err := url.Parse(urlStr)
206 | if err != nil || parsedURL.Host == "" {
207 | // If parsing fails or host is empty, return a safe default
208 | return "unknown"
209 | }
210 | return parsedURL.Host
211 | }
212 |
213 | // RecordRequest records metrics for a completed HTTP request
214 | // Note: Uses host extraction to prevent Prometheus cardinality issues with dynamic URL segments
215 | func RecordRequest(result *Result) {
216 | requestsTotal.Inc()
217 | host := extractHost(result.Request.Url)
218 |
219 | if result.ErrorMsg != "" {
220 | errorsTotal.WithLabelValues(host).Inc()
221 | } else {
222 | requestDuration.WithLabelValues(host).Observe(result.Latency.Seconds())
223 | responseStatus.WithLabelValues(http.StatusText(result.StatusCode), host).Inc()
224 | }
225 | }
226 |
227 | // SetWorkerPoolSize sets the worker pool size metric
228 | func SetWorkerPoolSize(size int) {
229 | workerPoolSize.Set(float64(size))
230 | }
231 |
232 | // SetPacerPhase sets the current pacer phase
233 | func SetPacerPhase(phase string, rate float64) {
234 | pacerPhase.WithLabelValues(phase).Set(rate)
235 | }
236 |
237 | // MonitorQueueSizes monitors the request and result queue sizes
238 | func MonitorQueueSizes(requests chan *Request, results chan *Result, done chan bool) {
239 | ticker := time.NewTicker(1 * time.Second)
240 | defer ticker.Stop()
241 |
242 | for {
243 | select {
244 | case <-done:
245 | return
246 | case <-ticker.C:
247 | requestQueueSize.Set(float64(len(requests)))
248 | resultQueueSize.Set(float64(len(results)))
249 | }
250 | }
251 | }
252 |
--------------------------------------------------------------------------------
/pkg/metrics_test.go:
--------------------------------------------------------------------------------
1 | /*
2 | ripley
3 | Copyright (C) 2021 loveholidays
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU General Public License as published by
7 | the Free Software Foundation, either version 3 of the License, or
8 | (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU General Public License for more details.
14 |
15 | You should have received a copy of the GNU General Public License
16 | along with this program. If not, see .
17 | */
18 |
19 | package ripley
20 |
21 | import (
22 | "io"
23 | "net/http"
24 | "strings"
25 | "testing"
26 | "time"
27 | )
28 |
29 | func TestNewMetricsRecorder_Disabled(t *testing.T) {
30 | config := MetricsConfig{
31 | Enabled: false,
32 | Address: "localhost:9999",
33 | }
34 |
35 | recorder := NewMetricsRecorder(config, 10)
36 |
37 | if _, ok := recorder.(*noopRecorder); !ok {
38 | t.Errorf("Expected noopRecorder, got %T", recorder)
39 | }
40 | }
41 |
42 | func TestNewMetricsRecorder_Enabled(t *testing.T) {
43 | config := MetricsConfig{
44 | Enabled: true,
45 | Address: "localhost:18081", // Use different port to avoid conflicts
46 | }
47 |
48 | recorder := NewMetricsRecorder(config, 10)
49 |
50 | if _, ok := recorder.(*prometheusRecorder); !ok {
51 | t.Errorf("Expected prometheusRecorder, got %T", recorder)
52 | }
53 |
54 | // Give server time to start
55 | time.Sleep(100 * time.Millisecond)
56 |
57 | // Verify metrics endpoint is accessible
58 | resp, err := http.Get("http://localhost:18081/metrics")
59 | if err != nil {
60 | t.Fatalf("Failed to access metrics endpoint: %v", err)
61 | }
62 | defer func() {
63 | if err := resp.Body.Close(); err != nil {
64 | t.Errorf("Failed to close response body: %v", err)
65 | }
66 | }()
67 |
68 | if resp.StatusCode != http.StatusOK {
69 | t.Errorf("Expected status 200, got %d", resp.StatusCode)
70 | }
71 |
72 | // Verify it returns Prometheus format
73 | body, _ := io.ReadAll(resp.Body)
74 | if !strings.Contains(string(body), "ripley_") {
75 | t.Error("Metrics endpoint doesn't contain ripley metrics")
76 | }
77 | }
78 |
79 | func TestNoopRecorder_RecordRequest(t *testing.T) {
80 | recorder := &noopRecorder{}
81 | req := &Request{
82 | Url: "http://example.com",
83 | Method: "GET",
84 | }
85 | result := &Result{
86 | Request: req,
87 | StatusCode: 200,
88 | Latency: 100 * time.Millisecond,
89 | }
90 |
91 | // Should not panic
92 | recorder.RecordRequest(result)
93 | }
94 |
95 | func TestNoopRecorder_StartMonitoring(t *testing.T) {
96 | recorder := &noopRecorder{}
97 | requests := make(chan *Request, 1)
98 | results := make(chan *Result, 1)
99 |
100 | cleanup := recorder.StartMonitoring(requests, results)
101 |
102 | // Should not panic
103 | cleanup()
104 | }
105 |
106 | func TestPrometheusRecorder_RecordRequest(t *testing.T) {
107 | config := MetricsConfig{
108 | Enabled: true,
109 | Address: "localhost:18082",
110 | }
111 |
112 | recorder := NewMetricsRecorder(config, 10)
113 |
114 | // Give server time to start
115 | time.Sleep(100 * time.Millisecond)
116 |
117 | req := &Request{
118 | Url: "http://test.example.com/api",
119 | Method: "GET",
120 | }
121 |
122 | result := &Result{
123 | Request: req,
124 | StatusCode: 200,
125 | Latency: 50 * time.Millisecond,
126 | }
127 |
128 | // Record a request
129 | recorder.RecordRequest(result)
130 |
131 | // Fetch metrics
132 | resp, err := http.Get("http://localhost:18082/metrics")
133 | if err != nil {
134 | t.Fatalf("Failed to get metrics: %v", err)
135 | }
136 | defer func() {
137 | if err := resp.Body.Close(); err != nil {
138 | t.Errorf("Failed to close response body: %v", err)
139 | }
140 | }()
141 |
142 | body, _ := io.ReadAll(resp.Body)
143 | metrics := string(body)
144 |
145 | // Check that request was recorded
146 | if !strings.Contains(metrics, "ripley_requests_total") {
147 | t.Error("ripley_requests_total metric not found")
148 | }
149 |
150 | if !strings.Contains(metrics, "ripley_request_duration_seconds") {
151 | t.Error("ripley_request_duration_seconds metric not found")
152 | }
153 |
154 | if !strings.Contains(metrics, "ripley_response_status_total") {
155 | t.Error("ripley_response_status_total metric not found")
156 | }
157 |
158 | // Verify host label is used (not full URL)
159 | if !strings.Contains(metrics, `host="test.example.com"`) {
160 | t.Error("Expected host label with value 'test.example.com'")
161 | }
162 | }
163 |
164 | func TestPrometheusRecorder_RecordRequestWithError(t *testing.T) {
165 | config := MetricsConfig{
166 | Enabled: true,
167 | Address: "localhost:18083",
168 | }
169 |
170 | recorder := NewMetricsRecorder(config, 10)
171 |
172 | // Give server time to start
173 | time.Sleep(100 * time.Millisecond)
174 |
175 | req := &Request{
176 | Url: "http://test.example.com/error",
177 | Method: "GET",
178 | }
179 |
180 | result := &Result{
181 | Request: req,
182 | StatusCode: 0,
183 | ErrorMsg: "connection refused",
184 | }
185 |
186 | // Record a failed request
187 | recorder.RecordRequest(result)
188 |
189 | // Fetch metrics
190 | resp, err := http.Get("http://localhost:18083/metrics")
191 | if err != nil {
192 | t.Fatalf("Failed to get metrics: %v", err)
193 | }
194 | defer func() {
195 | if err := resp.Body.Close(); err != nil {
196 | t.Errorf("Failed to close response body: %v", err)
197 | }
198 | }()
199 |
200 | body, _ := io.ReadAll(resp.Body)
201 | metrics := string(body)
202 |
203 | // Check that error was recorded
204 | if !strings.Contains(metrics, "ripley_errors_total") {
205 | t.Error("ripley_errors_total metric not found")
206 | }
207 | }
208 |
209 | func TestPrometheusRecorder_StartMonitoring(t *testing.T) {
210 | config := MetricsConfig{
211 | Enabled: true,
212 | Address: "localhost:18084",
213 | }
214 |
215 | promRecorder := NewMetricsRecorder(config, 10).(*prometheusRecorder)
216 |
217 | // Give server time to start
218 | time.Sleep(100 * time.Millisecond)
219 |
220 | requests := make(chan *Request, 10)
221 | results := make(chan *Result, 10)
222 |
223 | // Add some items to channels
224 | requests <- &Request{Url: "http://test.com", Method: "GET"}
225 | requests <- &Request{Url: "http://test.com", Method: "GET"}
226 | results <- &Result{StatusCode: 200}
227 |
228 | cleanup := promRecorder.StartMonitoring(requests, results)
229 |
230 | // Wait for monitoring to record queue sizes
231 | time.Sleep(1500 * time.Millisecond)
232 |
233 | // Fetch metrics
234 | resp, err := http.Get("http://localhost:18084/metrics")
235 | if err != nil {
236 | t.Fatalf("Failed to get metrics: %v", err)
237 | }
238 | defer func() {
239 | if err := resp.Body.Close(); err != nil {
240 | t.Errorf("Failed to close response body: %v", err)
241 | }
242 | }()
243 |
244 | body, _ := io.ReadAll(resp.Body)
245 | metrics := string(body)
246 |
247 | // Check that queue metrics are present
248 | if !strings.Contains(metrics, "ripley_request_queue_size") {
249 | t.Error("ripley_request_queue_size metric not found")
250 | }
251 |
252 | if !strings.Contains(metrics, "ripley_result_queue_size") {
253 | t.Error("ripley_result_queue_size metric not found")
254 | }
255 |
256 | // Cleanup should not panic
257 | cleanup()
258 |
259 | // Wait for cleanup
260 | time.Sleep(100 * time.Millisecond)
261 | }
262 |
263 | func TestStartMetricsServer_Disabled(t *testing.T) {
264 | config := MetricsConfig{
265 | Enabled: false,
266 | Address: "localhost:9999",
267 | }
268 |
269 | errChan := StartMetricsServer(config)
270 |
271 | // Should immediately close channel
272 | select {
273 | case err, ok := <-errChan:
274 | if ok {
275 | t.Errorf("Expected closed channel, got error: %v", err)
276 | }
277 | case <-time.After(100 * time.Millisecond):
278 | t.Error("Channel should be closed immediately when disabled")
279 | }
280 | }
281 |
282 | func TestStartMetricsServer_PortInUse(t *testing.T) {
283 | // Start a server on the test port
284 | testServer := &http.Server{Addr: "localhost:18085"}
285 | go func() {
286 | _ = testServer.ListenAndServe()
287 | }()
288 | defer func() {
289 | _ = testServer.Close()
290 | }()
291 |
292 | // Give server time to bind
293 | time.Sleep(100 * time.Millisecond)
294 |
295 | // Try to start metrics server on same port
296 | config := MetricsConfig{
297 | Enabled: true,
298 | Address: "localhost:18085",
299 | }
300 |
301 | errChan := StartMetricsServer(config)
302 |
303 | // Should receive an error
304 | select {
305 | case err := <-errChan:
306 | if err == nil {
307 | t.Error("Expected error for port in use, got nil")
308 | }
309 | if !strings.Contains(err.Error(), "address already in use") &&
310 | !strings.Contains(err.Error(), "bind") {
311 | t.Errorf("Expected 'address already in use' error, got: %v", err)
312 | }
313 | case <-time.After(2 * time.Second):
314 | t.Error("Timeout waiting for error from metrics server")
315 | }
316 | }
317 |
318 | func TestSetWorkerPoolSize(t *testing.T) {
319 | config := MetricsConfig{
320 | Enabled: true,
321 | Address: "localhost:18086",
322 | }
323 |
324 | NewMetricsRecorder(config, 42)
325 |
326 | // Give server time to start
327 | time.Sleep(100 * time.Millisecond)
328 |
329 | // Fetch metrics
330 | resp, err := http.Get("http://localhost:18086/metrics")
331 | if err != nil {
332 | t.Fatalf("Failed to get metrics: %v", err)
333 | }
334 | defer func() {
335 | if err := resp.Body.Close(); err != nil {
336 | t.Errorf("Failed to close response body: %v", err)
337 | }
338 | }()
339 |
340 | body, _ := io.ReadAll(resp.Body)
341 | metrics := string(body)
342 |
343 | // Check that worker pool size is set
344 | if !strings.Contains(metrics, "ripley_worker_pool_size 42") {
345 | t.Error("Worker pool size not correctly set in metrics")
346 | }
347 | }
348 |
349 | func TestExtractHost(t *testing.T) {
350 | tests := []struct {
351 | name string
352 | url string
353 | expected string
354 | }{
355 | {
356 | name: "simple http URL",
357 | url: "http://example.com/path",
358 | expected: "example.com",
359 | },
360 | {
361 | name: "https with port",
362 | url: "https://example.com:8080/api/v1/users",
363 | expected: "example.com:8080",
364 | },
365 | {
366 | name: "with query params and path",
367 | url: "http://api.example.com/users/123?token=abc&id=456",
368 | expected: "api.example.com",
369 | },
370 | {
371 | name: "localhost with port",
372 | url: "http://localhost:8080/test",
373 | expected: "localhost:8080",
374 | },
375 | {
376 | name: "IP address",
377 | url: "http://192.168.1.1:9090/metrics",
378 | expected: "192.168.1.1:9090",
379 | },
380 | {
381 | name: "invalid URL",
382 | url: "not a valid url",
383 | expected: "unknown",
384 | },
385 | }
386 |
387 | for _, tt := range tests {
388 | t.Run(tt.name, func(t *testing.T) {
389 | result := extractHost(tt.url)
390 | if result != tt.expected {
391 | t.Errorf("extractHost(%q) = %q, want %q", tt.url, result, tt.expected)
392 | }
393 | })
394 | }
395 | }
396 |
397 | func TestMetricsRecorder_MultipleRequests(t *testing.T) {
398 | config := MetricsConfig{
399 | Enabled: true,
400 | Address: "localhost:18087",
401 | }
402 |
403 | recorder := NewMetricsRecorder(config, 10)
404 |
405 | // Give server time to start
406 | time.Sleep(100 * time.Millisecond)
407 |
408 | // Get initial count
409 | resp1, err := http.Get("http://localhost:18087/metrics")
410 | if err != nil {
411 | t.Fatalf("Failed to get initial metrics: %v", err)
412 | }
413 | body1, _ := io.ReadAll(resp1.Body)
414 | _ = resp1.Body.Close()
415 |
416 | initialMetrics := string(body1)
417 | initialHasRequests := strings.Contains(initialMetrics, "ripley_requests_total")
418 |
419 | // Record multiple requests
420 | for i := 0; i < 5; i++ {
421 | req := &Request{
422 | Url: "http://test.example.com/multi",
423 | Method: "GET",
424 | }
425 |
426 | result := &Result{
427 | Request: req,
428 | StatusCode: 200,
429 | Latency: time.Duration(10*i) * time.Millisecond,
430 | }
431 |
432 | recorder.RecordRequest(result)
433 | }
434 |
435 | // Fetch metrics after recording
436 | resp, err := http.Get("http://localhost:18087/metrics")
437 | if err != nil {
438 | t.Fatalf("Failed to get metrics: %v", err)
439 | }
440 | defer func() {
441 | if err := resp.Body.Close(); err != nil {
442 | t.Errorf("Failed to close response body: %v", err)
443 | }
444 | }()
445 |
446 | body, _ := io.ReadAll(resp.Body)
447 | metrics := string(body)
448 |
449 | // Check that requests were counted (total should be >= 5)
450 | if !strings.Contains(metrics, "ripley_requests_total") {
451 | t.Error("ripley_requests_total metric not found")
452 | }
453 |
454 | // If we had no requests initially, we should have exactly 5 now
455 | if !initialHasRequests && !strings.Contains(metrics, "ripley_requests_total 5") {
456 | t.Error("Expected ripley_requests_total to be 5 for new instance")
457 | }
458 | }
459 |
--------------------------------------------------------------------------------
/tools/linkerdxripley/pkg/converter/converter_test.go:
--------------------------------------------------------------------------------
1 | package converter
2 |
3 | import (
4 | "encoding/json"
5 | "testing"
6 | "time"
7 |
8 | ripley "github.com/loveholidays/ripley/pkg"
9 | "github.com/loveholidays/ripley/tools/linkerdxripley/pkg/linkerd"
10 | )
11 |
12 | func TestConverter_ConvertToRipley(t *testing.T) {
13 | t.Run("successful conversions", func(t *testing.T) {
14 | testSuccessfulConversions(t)
15 | })
16 |
17 | t.Run("error cases", func(t *testing.T) {
18 | testConversionErrors(t)
19 | })
20 | }
21 |
22 | func testSuccessfulConversions(t *testing.T) {
23 | t.Run("basic conversion tests", func(t *testing.T) {
24 | testBasicConversions(t)
25 | })
26 |
27 | t.Run("HTTPS upgrade tests", func(t *testing.T) {
28 | testHTTPSUpgradeConversions(t)
29 | })
30 | }
31 |
32 | func testBasicConversions(t *testing.T) {
33 | conv := New()
34 |
35 | tests := []conversionTest{
36 | {
37 | name: "basic conversion without host change",
38 | linkerdReq: createFullLinkerdRequest(),
39 | newHost: "",
40 | expected: &ripley.Request{
41 | Method: "GET",
42 | Url: "http://api-service.test.svc.cluster.local/api/v1/data?id=12345",
43 | Timestamp: mustParseTime("2025-09-03T15:30:32.928995068Z"),
44 | Headers: map[string]string{
45 | "User-Agent": "TestClient/1.0",
46 | },
47 | },
48 | },
49 | {
50 | name: "conversion with host change",
51 | linkerdReq: createSimpleLinkerdRequest("POST", "api.test.com", "http://api.test.com/endpoint", "TestAgent/1.0"),
52 | newHost: "localhost:8080",
53 | expected: &ripley.Request{
54 | Method: "POST",
55 | Url: "http://localhost:8080/endpoint",
56 | Timestamp: mustParseTime("2025-09-03T15:30:32.928995068Z"),
57 | Headers: map[string]string{
58 | "User-Agent": "TestAgent/1.0",
59 | },
60 | },
61 | },
62 | {
63 | name: "conversion without user agent",
64 | linkerdReq: createSimpleLinkerdRequest("GET", "api.test.com", "http://api.test.com/endpoint", ""),
65 | newHost: "",
66 | expected: &ripley.Request{
67 | Method: "GET",
68 | Url: "http://api.test.com/endpoint",
69 | Timestamp: mustParseTime("2025-09-03T15:30:32.928995068Z"),
70 | Headers: map[string]string{},
71 | },
72 | },
73 | {
74 | name: "conversion with complex query parameters",
75 | linkerdReq: createSimpleLinkerdRequest("GET", "search-api.test.com", "http://search-api.test.com/search?q=test&category=books&page=1&limit=10&sort=price", "TestBrowser/2.0"),
76 | newHost: "staging.search-api.test.com:9000",
77 | expected: &ripley.Request{
78 | Method: "GET",
79 | Url: "http://staging.search-api.test.com:9000/search?q=test&category=books&page=1&limit=10&sort=price",
80 | Timestamp: mustParseTime("2025-09-03T15:30:32.928995068Z"),
81 | Headers: map[string]string{
82 | "User-Agent": "TestBrowser/2.0",
83 | },
84 | },
85 | },
86 | }
87 |
88 | runConversionTests(t, conv, tests)
89 | }
90 |
91 | func testHTTPSUpgradeConversions(t *testing.T) {
92 | conv := New()
93 |
94 | tests := []conversionTest{
95 | {
96 | name: "HTTP to HTTPS upgrade without host change",
97 | linkerdReq: createSimpleLinkerdRequest("GET", "api.test.com", "http://api.test.com/secure-endpoint", "TestAgent/1.0"),
98 | newHost: "",
99 | upgradeHTTPS: true,
100 | expected: &ripley.Request{
101 | Method: "GET",
102 | Url: "https://api.test.com/secure-endpoint",
103 | Timestamp: mustParseTime("2025-09-03T15:30:32.928995068Z"),
104 | Headers: map[string]string{
105 | "User-Agent": "TestAgent/1.0",
106 | },
107 | },
108 | },
109 | {
110 | name: "HTTP to HTTPS upgrade with host change",
111 | linkerdReq: createSimpleLinkerdRequest("GET", "api.test.com", "http://api.test.com/secure-endpoint", "TestAgent/1.0"),
112 | newHost: "localhost:8443",
113 | upgradeHTTPS: true,
114 | expected: &ripley.Request{
115 | Method: "GET",
116 | Url: "https://localhost:8443/secure-endpoint",
117 | Timestamp: mustParseTime("2025-09-03T15:30:32.928995068Z"),
118 | Headers: map[string]string{
119 | "User-Agent": "TestAgent/1.0",
120 | },
121 | },
122 | },
123 | {
124 | name: "HTTPS request remains HTTPS (no downgrade)",
125 | linkerdReq: createSimpleLinkerdRequest("GET", "secure-api.test.com", "https://secure-api.test.com/endpoint", "TestAgent/1.0"),
126 | newHost: "localhost:8443",
127 | upgradeHTTPS: true,
128 | expected: &ripley.Request{
129 | Method: "GET",
130 | Url: "https://localhost:8443/endpoint",
131 | Timestamp: mustParseTime("2025-09-03T15:30:32.928995068Z"),
132 | Headers: map[string]string{
133 | "User-Agent": "TestAgent/1.0",
134 | },
135 | },
136 | },
137 | }
138 |
139 | runConversionTests(t, conv, tests)
140 | }
141 |
142 | type conversionTest struct {
143 | name string
144 | linkerdReq linkerd.Request
145 | newHost string
146 | upgradeHTTPS bool
147 | expected *ripley.Request
148 | }
149 |
150 | func createFullLinkerdRequest() linkerd.Request {
151 | return linkerd.Request{
152 | ClientAddr: "192.168.1.100:12345",
153 | ClientID: "test-service.default.serviceaccount.identity.linkerd.cluster.local",
154 | Host: "api-service.test.svc.cluster.local",
155 | Method: "GET",
156 | ProcessingNs: "50000",
157 | RequestBytes: "0",
158 | Status: 200,
159 | Timestamp: "2025-09-03T15:30:32.928995068Z",
160 | TotalNs: "2500000",
161 | TraceID: "abc123def456",
162 | URI: "http://api-service.test.svc.cluster.local/api/v1/data?id=12345",
163 | UserAgent: "TestClient/1.0",
164 | Version: "HTTP/2.0",
165 | }
166 | }
167 |
168 | func createSimpleLinkerdRequest(method, host, uri, userAgent string) linkerd.Request {
169 | return linkerd.Request{
170 | Method: method,
171 | Host: host,
172 | Timestamp: "2025-09-03T15:30:32.928995068Z",
173 | URI: uri,
174 | UserAgent: userAgent,
175 | }
176 | }
177 |
178 | func runConversionTests(t *testing.T, conv *Converter, tests []conversionTest) {
179 | for _, tt := range tests {
180 | t.Run(tt.name, func(t *testing.T) {
181 | result, err := conv.ConvertToRipley(tt.linkerdReq, tt.newHost, tt.upgradeHTTPS)
182 | assertNoError(t, err)
183 | assertConversionResult(t, result, tt.expected)
184 | })
185 | }
186 | }
187 |
188 | func testConversionErrors(t *testing.T) {
189 | conv := New()
190 |
191 | tests := []struct {
192 | name string
193 | linkerdReq linkerd.Request
194 | newHost string
195 | }{
196 | {
197 | name: "conversion with invalid timestamp",
198 | linkerdReq: linkerd.Request{
199 | Method: "GET",
200 | Timestamp: "invalid-timestamp",
201 | URI: "http://api.test.com/endpoint",
202 | },
203 | newHost: "",
204 | },
205 | {
206 | name: "conversion with invalid URI and new host",
207 | linkerdReq: linkerd.Request{
208 | Method: "GET",
209 | Timestamp: "2025-09-03T15:30:32.928995068Z",
210 | URI: "://invalid-uri",
211 | },
212 | newHost: "localhost:8080",
213 | },
214 | }
215 |
216 | for _, tt := range tests {
217 | t.Run(tt.name, func(t *testing.T) {
218 | _, err := conv.ConvertToRipley(tt.linkerdReq, tt.newHost, false)
219 | assertError(t, err)
220 | })
221 | }
222 | }
223 |
224 | func assertNoError(t *testing.T, err error) {
225 | if err != nil {
226 | t.Errorf("unexpected error: %v", err)
227 | }
228 | }
229 |
230 | func assertError(t *testing.T, err error) {
231 | if err == nil {
232 | t.Errorf("expected error but got none")
233 | }
234 | }
235 |
236 | func assertConversionResult(t *testing.T, result, expected *ripley.Request) {
237 | if result.Method != expected.Method {
238 | t.Errorf("Method: got %s, want %s", result.Method, expected.Method)
239 | }
240 |
241 | if result.Url != expected.Url {
242 | t.Errorf("URL: got %s, want %s", result.Url, expected.Url)
243 | }
244 |
245 | if !result.Timestamp.Equal(expected.Timestamp) {
246 | t.Errorf("Timestamp: got %v, want %v", result.Timestamp, expected.Timestamp)
247 | }
248 |
249 | assertHeadersMatch(t, result.Headers, expected.Headers)
250 | }
251 |
252 | func assertHeadersMatch(t *testing.T, result, expected map[string]string) {
253 | if len(result) != len(expected) {
254 | t.Errorf("Headers length: got %d, want %d", len(result), len(expected))
255 | return
256 | }
257 |
258 | for k, v := range expected {
259 | if result[k] != v {
260 | t.Errorf("Header %s: got %s, want %s", k, result[k], v)
261 | }
262 | }
263 | }
264 |
265 | func TestConverter_parseTimestamp(t *testing.T) {
266 | conv := New()
267 |
268 | tests := []struct {
269 | name string
270 | input string
271 | expectError bool
272 | }{
273 | {"valid RFC3339Nano", "2025-09-03T15:30:32.928995068Z", false},
274 | {"valid RFC3339", "2025-09-03T15:30:32Z", false},
275 | {"invalid format", "2025/09/03 15:30:32", true},
276 | {"empty string", "", true},
277 | }
278 |
279 | for _, tt := range tests {
280 | t.Run(tt.name, func(t *testing.T) {
281 | _, err := conv.parseTimestamp(tt.input)
282 | if tt.expectError && err == nil {
283 | t.Errorf("expected error but got none")
284 | }
285 | if !tt.expectError && err != nil {
286 | t.Errorf("unexpected error: %v", err)
287 | }
288 | })
289 | }
290 | }
291 |
292 | func TestConverter_buildTargetURL(t *testing.T) {
293 | conv := New()
294 |
295 | tests := []struct {
296 | name string
297 | originalURI string
298 | newHost string
299 | expected string
300 | expectError bool
301 | }{
302 | {
303 | name: "no host change",
304 | originalURI: "http://test.com/path",
305 | newHost: "",
306 | expected: "http://test.com/path",
307 | expectError: false,
308 | },
309 | {
310 | name: "host change with port",
311 | originalURI: "http://test.com/path?query=value",
312 | newHost: "localhost:8080",
313 | expected: "http://localhost:8080/path?query=value",
314 | expectError: false,
315 | },
316 | {
317 | name: "invalid URI",
318 | originalURI: "://invalid",
319 | newHost: "localhost",
320 | expected: "",
321 | expectError: true,
322 | },
323 | }
324 |
325 | for _, tt := range tests {
326 | t.Run(tt.name, func(t *testing.T) {
327 | result, err := conv.buildTargetURL(tt.originalURI, tt.newHost, false)
328 |
329 | if tt.expectError {
330 | if err == nil {
331 | t.Errorf("expected error but got none")
332 | }
333 | return
334 | }
335 |
336 | if err != nil {
337 | t.Errorf("unexpected error: %v", err)
338 | return
339 | }
340 |
341 | if result != tt.expected {
342 | t.Errorf("got %s, want %s", result, tt.expected)
343 | }
344 | })
345 | }
346 | }
347 |
348 | func TestConverter_buildHeaders(t *testing.T) {
349 | conv := New()
350 |
351 | tests := []struct {
352 | name string
353 | linkerd linkerd.Request
354 | expected map[string]string
355 | }{
356 | {
357 | name: "user agent present",
358 | linkerd: linkerd.Request{
359 | UserAgent: "TestAgent/1.0",
360 | Host: "test.com",
361 | },
362 | expected: map[string]string{
363 | "User-Agent": "TestAgent/1.0",
364 | },
365 | },
366 | {
367 | name: "only user agent",
368 | linkerd: linkerd.Request{
369 | UserAgent: "TestAgent/1.0",
370 | Host: "",
371 | },
372 | expected: map[string]string{
373 | "User-Agent": "TestAgent/1.0",
374 | },
375 | },
376 | {
377 | name: "no user agent with host",
378 | linkerd: linkerd.Request{
379 | UserAgent: "",
380 | Host: "test.com",
381 | },
382 | expected: map[string]string{},
383 | },
384 | {
385 | name: "no headers",
386 | linkerd: linkerd.Request{
387 | UserAgent: "",
388 | Host: "",
389 | },
390 | expected: map[string]string{},
391 | },
392 | }
393 |
394 | for _, tt := range tests {
395 | t.Run(tt.name, func(t *testing.T) {
396 | result := conv.buildHeaders(tt.linkerd)
397 | assertHeadersMatch(t, result, tt.expected)
398 | })
399 | }
400 | }
401 |
402 | func TestJSONSerialization(t *testing.T) {
403 | conv := New()
404 |
405 | linkerdReq := linkerd.Request{
406 | Method: "GET",
407 | Host: "api.test.com",
408 | Timestamp: "2025-09-03T15:30:32.928995068Z",
409 | URI: "http://api.test.com/endpoint",
410 | UserAgent: "TestAgent/1.0",
411 | }
412 |
413 | ripleyReq, err := conv.ConvertToRipley(linkerdReq, "", false)
414 | if err != nil {
415 | t.Fatalf("conversion failed: %v", err)
416 | }
417 |
418 | jsonData, err := json.Marshal(ripleyReq)
419 | if err != nil {
420 | t.Fatalf("JSON marshaling failed: %v", err)
421 | }
422 |
423 | var unmarshaled ripley.Request
424 | err = json.Unmarshal(jsonData, &unmarshaled)
425 | if err != nil {
426 | t.Fatalf("JSON unmarshaling failed: %v", err)
427 | }
428 |
429 | if unmarshaled.Method != ripleyReq.Method {
430 | t.Errorf("Method after JSON round-trip: got %s, want %s", unmarshaled.Method, ripleyReq.Method)
431 | }
432 |
433 | if unmarshaled.Url != ripleyReq.Url {
434 | t.Errorf("URL after JSON round-trip: got %s, want %s", unmarshaled.Url, ripleyReq.Url)
435 | }
436 | }
437 |
438 | func mustParseTime(timeStr string) time.Time {
439 | t, err := time.Parse(time.RFC3339Nano, timeStr)
440 | if err != nil {
441 | panic(err)
442 | }
443 | return t
444 | }
445 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------