summaryrefslogtreecommitdiffhomepage
path: root/test/benchmarks/network/httpd_test.go
blob: fe23ca94905e0827d57bd5bc14bda06ab9ba6ede (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
// Copyright 2020 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package network

import (
	"context"
	"fmt"
	"regexp"
	"strconv"
	"testing"

	"gvisor.dev/gvisor/pkg/test/dockerutil"
	"gvisor.dev/gvisor/test/benchmarks/harness"
)

// see Dockerfile '//images/benchmarks/httpd'.
var docs = map[string]string{
	"notfound": "notfound",
	"1Kb":      "latin1k.txt",
	"10Kb":     "latin10k.txt",
	"100Kb":    "latin100k.txt",
	"1000Kb":   "latin1000k.txt",
	"1Mb":      "latin1024k.txt",
	"10Mb":     "latin10240k.txt",
}

// BenchmarkHttpdConcurrency iterates the concurrency argument and tests
// how well the runtime under test handles requests in parallel.
func BenchmarkHttpdConcurrency(b *testing.B) {
	// Grab a machine for the client and server.
	clientMachine, err := h.GetMachine()
	if err != nil {
		b.Fatalf("failed to get client: %v", err)
	}
	defer clientMachine.CleanUp()

	serverMachine, err := h.GetMachine()
	if err != nil {
		b.Fatalf("failed to get server: %v", err)
	}
	defer serverMachine.CleanUp()

	// The test iterates over client concurrency, so set other parameters.
	requests := 10000
	concurrency := []int{1, 5, 10, 25}
	doc := docs["10Kb"]

	for _, c := range concurrency {
		b.Run(fmt.Sprintf("%d", c), func(b *testing.B) {
			runHttpd(b, clientMachine, serverMachine, doc, requests, c)
		})
	}
}

// BenchmarkHttpdDocSize iterates over different sized payloads, testing how
// well the runtime handles different payload sizes.
func BenchmarkHttpdDocSize(b *testing.B) {
	clientMachine, err := h.GetMachine()
	if err != nil {
		b.Fatalf("failed to get machine: %v", err)
	}
	defer clientMachine.CleanUp()

	serverMachine, err := h.GetMachine()
	if err != nil {
		b.Fatalf("failed to get machine: %v", err)
	}
	defer serverMachine.CleanUp()

	requests := 10000
	concurrency := 1

	for name, filename := range docs {
		b.Run(name, func(b *testing.B) {
			runHttpd(b, clientMachine, serverMachine, filename, requests, concurrency)
		})
	}
}

// runHttpd runs a single test run.
func runHttpd(b *testing.B, clientMachine, serverMachine harness.Machine, doc string, requests, concurrency int) {
	b.Helper()

	// Grab a container from the server.
	ctx := context.Background()
	server := serverMachine.GetContainer(ctx, b)
	defer server.CleanUp(ctx)

	// Copy the docs to /tmp and serve from there.
	cmd := "mkdir -p /tmp/html; cp -r /local /tmp/html/.; apache2 -X"
	port := 80

	// Start the server.
	server.Spawn(ctx, dockerutil.RunOpts{
		Image: "benchmarks/httpd",
		Ports: []int{port},
		Env: []string{
			// Standard environmental variables for httpd.
			"APACHE_RUN_DIR=/tmp",
			"APACHE_RUN_USER=nobody",
			"APACHE_RUN_GROUP=nogroup",
			"APACHE_LOG_DIR=/tmp",
			"APACHE_PID_FILE=/tmp/apache.pid",
		},
	}, "sh", "-c", cmd)

	ip, err := serverMachine.IPAddress()
	if err != nil {
		b.Fatalf("failed to find server ip: %v", err)
	}

	servingPort, err := server.FindPort(ctx, port)
	if err != nil {
		b.Fatalf("failed to find server port %d: %v", port, err)
	}

	// Check the server is serving.
	harness.WaitUntilServing(ctx, clientMachine, ip, servingPort)

	// Grab a client.
	client := clientMachine.GetNativeContainer(ctx, b)
	defer client.CleanUp(ctx)

	path := fmt.Sprintf("http://%s:%d/%s", ip, servingPort, doc)
	// See apachebench (ab) for flags.
	cmd = fmt.Sprintf("ab -n %d -c %d %s", requests, concurrency, path)

	b.ResetTimer()
	server.RestartProfiles()
	for i := 0; i < b.N; i++ {
		out, err := client.Run(ctx, dockerutil.RunOpts{
			Image: "benchmarks/ab",
		}, "sh", "-c", cmd)
		if err != nil {
			b.Fatalf("run failed with: %v", err)
		}

		b.StopTimer()

		// Parse and report custom metrics.
		transferRate, err := parseTransferRate(out)
		if err != nil {
			b.Logf("failed to parse transferrate: %v", err)
		}
		b.ReportMetric(transferRate*1024, "transfer_rate") // Convert from Kb/s to b/s.

		latency, err := parseLatency(out)
		if err != nil {
			b.Logf("failed to parse latency: %v", err)
		}
		b.ReportMetric(latency/1000, "mean_latency") // Convert from ms to s.

		reqPerSecond, err := parseRequestsPerSecond(out)
		if err != nil {
			b.Logf("failed to parse requests per second: %v", err)
		}
		b.ReportMetric(reqPerSecond, "requests_per_second")

		b.StartTimer()
	}
}

var transferRateRE = regexp.MustCompile(`Transfer rate:\s+(\d+\.?\d+?)\s+\[Kbytes/sec\]\s+received`)

// parseTransferRate parses transfer rate from apachebench output.
func parseTransferRate(data string) (float64, error) {
	match := transferRateRE.FindStringSubmatch(data)
	if len(match) < 2 {
		return 0, fmt.Errorf("failed get bandwidth: %s", data)
	}
	return strconv.ParseFloat(match[1], 64)
}

var latencyRE = regexp.MustCompile(`Total:\s+\d+\s+(\d+)\s+(\d+\.?\d+?)\s+\d+\s+\d+\s`)

// parseLatency parses latency from apachebench output.
func parseLatency(data string) (float64, error) {
	match := latencyRE.FindStringSubmatch(data)
	if len(match) < 2 {
		return 0, fmt.Errorf("failed get bandwidth: %s", data)
	}
	return strconv.ParseFloat(match[1], 64)
}

var requestsPerSecondRE = regexp.MustCompile(`Requests per second:\s+(\d+\.?\d+?)\s+`)

// parseRequestsPerSecond parses requests per second from apachebench output.
func parseRequestsPerSecond(data string) (float64, error) {
	match := requestsPerSecondRE.FindStringSubmatch(data)
	if len(match) < 2 {
		return 0, fmt.Errorf("failed get bandwidth: %s", data)
	}
	return strconv.ParseFloat(match[1], 64)
}

// Sample output from apachebench.
const sampleData = `This is ApacheBench, Version 2.3 <$Revision: 1826891 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking 10.10.10.10 (be patient).....done


Server Software:        Apache/2.4.38
Server Hostname:        10.10.10.10
Server Port:            80

Document Path:          /latin10k.txt
Document Length:        210 bytes

Concurrency Level:      1
Time taken for tests:   0.180 seconds
Complete requests:      100
Failed requests:        0
Non-2xx responses:      100
Total transferred:      38800 bytes
HTML transferred:       21000 bytes
Requests per second:    556.44 [#/sec] (mean)
Time per request:       1.797 [ms] (mean)
Time per request:       1.797 [ms] (mean, across all concurrent requests)
Transfer rate:          210.84 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    0   0.2      0       2
Processing:     1    2   1.0      1       8
Waiting:        1    1   1.0      1       7
Total:          1    2   1.2      1      10

Percentage of the requests served within a certain time (ms)
  50%      1
  66%      2
  75%      2
  80%      2
  90%      2
  95%      3
  98%      7
  99%     10
 100%     10 (longest request)`

// TestParsers checks the parsers work.
func TestParsers(t *testing.T) {
	want := 210.84
	got, err := parseTransferRate(sampleData)
	if err != nil {
		t.Fatalf("failed to parse transfer rate with error: %v", err)
	} else if got != want {
		t.Fatalf("parseTransferRate got: %f, want: %f", got, want)
	}

	want = 2.0
	got, err = parseLatency(sampleData)
	if err != nil {
		t.Fatalf("failed to parse transfer rate with error: %v", err)
	} else if got != want {
		t.Fatalf("parseLatency got: %f, want: %f", got, want)
	}

	want = 556.44
	got, err = parseRequestsPerSecond(sampleData)
	if err != nil {
		t.Fatalf("failed to parse transfer rate with error: %v", err)
	} else if got != want {
		t.Fatalf("parseRequestsPerSecond got: %f, want: %f", got, want)
	}
}