Debian Codegraph @

test/cpp/microbenchmarks/bm_chttp2_transport.cc

raw
1 /*
2 *
3 * Copyright 2015 gRPC authors.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 */
18
19 /* Microbenchmarks around CHTTP2 transport operations */
20
21 #include <string.h>
22
23 #include <memory>
24 #include <queue>
25 #include <sstream>
26
27 #include <benchmark/benchmark.h>
28
29 #include <grpc/support/alloc.h>
30 #include <grpc/support/log.h>
31 #include <grpc/support/string_util.h>
32 #include <grpcpp/support/channel_arguments.h>
33
34 #include "src/core/ext/transport/chttp2/transport/chttp2_transport.h"
35 #include "src/core/ext/transport/chttp2/transport/internal.h"
36 #include "src/core/lib/iomgr/closure.h"
37 #include "src/core/lib/resource_quota/api.h"
38 #include "src/core/lib/slice/slice_internal.h"
39 #include "test/core/util/test_config.h"
40 #include "test/cpp/microbenchmarks/helpers.h"
41 #include "test/cpp/util/test_config.h"
42
43 static auto* g_memory_allocator = new grpc_core::MemoryAllocator(
44 grpc_core::ResourceQuota::Default()->memory_quota()->CreateMemoryAllocator(
45 "test"));
46
47 ////////////////////////////////////////////////////////////////////////////////
48 // Helper classes
49 //
50
51 class PhonyEndpoint : public grpc_endpoint {
52 public:
53 PhonyEndpoint() {
54 static const grpc_endpoint_vtable my_vtable = {read,
55 write,
56 add_to_pollset,
57 add_to_pollset_set,
58 delete_from_pollset_set,
59 shutdown,
60 destroy,
61 get_peer,
62 get_local_address,
63 get_fd,
64 can_track_err};
65 grpc_endpoint::vtable = &my_vtable;
66 }
67
68 void PushInput(grpc_slice slice) {
69 if (read_cb_ == nullptr) {
70 GPR_ASSERT(!have_slice_);
71 buffered_slice_ = slice;
72 have_slice_ = true;
73 return;
74 }
75 grpc_slice_buffer_add(slices_, slice);
76 grpc_core::ExecCtx::Run(DEBUG_LOCATION, read_cb_, absl::OkStatus());
77 read_cb_ = nullptr;
78 }
79
80 private:
81 grpc_closure* read_cb_ = nullptr;
82 grpc_slice_buffer* slices_ = nullptr;
83 bool have_slice_ = false;
84 grpc_slice buffered_slice_;
85
86 void QueueRead(grpc_slice_buffer* slices, grpc_closure* cb) {
87 GPR_ASSERT(read_cb_ == nullptr);
88 if (have_slice_) {
89 have_slice_ = false;
90 grpc_slice_buffer_add(slices, buffered_slice_);
91 grpc_core::ExecCtx::Run(DEBUG_LOCATION, cb, absl::OkStatus());
92 return;
93 }
94 read_cb_ = cb;
95 slices_ = slices;
96 }
97
98 static void read(grpc_endpoint* ep, grpc_slice_buffer* slices,
99 grpc_closure* cb, bool /*urgent*/,
100 int /*min_progress_size*/) {
101 static_cast<PhonyEndpoint*>(ep)->QueueRead(slices, cb);
102 }
103
104 static void write(grpc_endpoint* /*ep*/, grpc_slice_buffer* /*slices*/,
105 grpc_closure* cb, void* /*arg*/, int /*max_frame_size*/) {
106 grpc_core::ExecCtx::Run(DEBUG_LOCATION, cb, absl::OkStatus());
107 }
108
109 static void add_to_pollset(grpc_endpoint* /*ep*/, grpc_pollset* /*pollset*/) {
110 }
111
112 static void add_to_pollset_set(grpc_endpoint* /*ep*/,
113 grpc_pollset_set* /*pollset*/) {}
114
115 static void delete_from_pollset_set(grpc_endpoint* /*ep*/,
116 grpc_pollset_set* /*pollset*/) {}
117
118 static void shutdown(grpc_endpoint* ep, grpc_error_handle why) {
119 grpc_core::ExecCtx::Run(DEBUG_LOCATION,
120 static_cast<PhonyEndpoint*>(ep)->read_cb_, why);
121 }
122
123 static void destroy(grpc_endpoint* ep) {
124 delete static_cast<PhonyEndpoint*>(ep);
125 }
126
127 static absl::string_view get_peer(grpc_endpoint* /*ep*/) { return "test"; }
128 static absl::string_view get_local_address(grpc_endpoint* /*ep*/) {
129 return "test";
130 }
131 static int get_fd(grpc_endpoint* /*ep*/) { return 0; }
132 static bool can_track_err(grpc_endpoint* /*ep*/) { return false; }
133 };
134
135 class Fixture {
136 public:
137 Fixture(const grpc::ChannelArguments& args, bool client) {
138 grpc_channel_args c_args = args.c_channel_args();
139 ep_ = new PhonyEndpoint;
140 auto final_args = grpc_core::CoreConfiguration::Get()
141 .channel_args_preconditioning()
142 .PreconditionChannelArgs(&c_args);
143 t_ = grpc_create_chttp2_transport(final_args, ep_, client);
144 grpc_chttp2_transport_start_reading(t_, nullptr, nullptr, nullptr);
145 FlushExecCtx();
146 }
147
148 void FlushExecCtx() { grpc_core::ExecCtx::Get()->Flush(); }
149
150 ~Fixture() { grpc_transport_destroy(t_); }
151
152 grpc_chttp2_transport* chttp2_transport() {
153 return reinterpret_cast<grpc_chttp2_transport*>(t_);
154 }
155 grpc_transport* transport() { return t_; }
156
157 void PushInput(grpc_slice slice) { ep_->PushInput(slice); }
158
159 private:
160 PhonyEndpoint* ep_;
161 grpc_transport* t_;
162 };
163
164 class TestClosure : public grpc_closure {
165 public:
166 virtual ~TestClosure() {}
167 };
168
169 template <class F>
170 std::unique_ptr<TestClosure> MakeTestClosure(F f) {
171 struct C : public TestClosure {
172 explicit C(const F& f) : f_(f) {
173 GRPC_CLOSURE_INIT(this, Execute, this, nullptr);
174 }
175 F f_;
176 static void Execute(void* arg, grpc_error_handle error) {
177 static_cast<C*>(arg)->f_(error);
178 }
179 };
180 return std::unique_ptr<TestClosure>(new C(f));
181 }
182
183 template <class F>
184 grpc_closure* MakeOnceClosure(F f) {
185 struct C : public grpc_closure {
186 explicit C(const F& f) : f_(f) {}
187 F f_;
188 static void Execute(void* arg, grpc_error_handle error) {
189 static_cast<C*>(arg)->f_(error);
190 delete static_cast<C*>(arg);
191 }
192 };
193 auto* c = new C{f};
194 return GRPC_CLOSURE_INIT(c, C::Execute, c, nullptr);
195 }
196
197 class Stream {
198 public:
199 explicit Stream(Fixture* f) : f_(f) {
200 stream_size_ = grpc_transport_stream_size(f->transport());
201 stream_ = gpr_malloc(stream_size_);
202 arena_ = grpc_core::Arena::Create(4096, g_memory_allocator);
203 }
204
205 ~Stream() {
206 gpr_event_wait(&done_, gpr_inf_future(GPR_CLOCK_REALTIME));
207 gpr_free(stream_);
208 arena_->Destroy();
209 }
210
211 void Init(benchmark::State& state) {
212 GRPC_STREAM_REF_INIT(&refcount_, 1, &Stream::FinishDestroy, this,
213 "test_stream");
214 gpr_event_init(&done_);
215 memset(stream_, 0, stream_size_);
216 if ((state.iterations() & 0xffff) == 0) {
217 arena_->Destroy();
218 arena_ = grpc_core::Arena::Create(4096, g_memory_allocator);
219 }
220 grpc_transport_init_stream(f_->transport(),
221 static_cast<grpc_stream*>(stream_), &refcount_,
222 nullptr, arena_);
223 }
224
225 void DestroyThen(grpc_closure* closure) {
226 destroy_closure_ = closure;
227 #ifndef NDEBUG
228 grpc_stream_unref(&refcount_, "DestroyThen");
229 #else
230 grpc_stream_unref(&refcount_);
231 #endif
232 }
233
234 void Op(grpc_transport_stream_op_batch* op) {
235 grpc_transport_perform_stream_op(f_->transport(),
236 static_cast<grpc_stream*>(stream_), op);
237 }
238
239 grpc_chttp2_stream* chttp2_stream() {
240 return static_cast<grpc_chttp2_stream*>(stream_);
241 }
242
243 private:
244 static void FinishDestroy(void* arg, grpc_error_handle /*error*/) {
245 auto stream = static_cast<Stream*>(arg);
246 grpc_transport_destroy_stream(stream->f_->transport(),
247 static_cast<grpc_stream*>(stream->stream_),
248 stream->destroy_closure_);
249 gpr_event_set(&stream->done_, reinterpret_cast<void*>(1));
250 }
251
252 Fixture* f_;
253 grpc_stream_refcount refcount_;
254 grpc_core::Arena* arena_;
255 size_t stream_size_;
256 void* stream_;
257 grpc_closure* destroy_closure_ = nullptr;
258 gpr_event done_;
259 };
260
261 ////////////////////////////////////////////////////////////////////////////////
262 // Benchmarks
263 //
264 std::vector<std::unique_ptr<gpr_event>> done_events;
265
266 static void BM_StreamCreateDestroy(benchmark::State& state) {
267 grpc_core::ExecCtx exec_ctx;
268 Fixture f(grpc::ChannelArguments(), true);
269 auto* s = new Stream(&f);
270 grpc_transport_stream_op_batch op;
271 grpc_transport_stream_op_batch_payload op_payload(nullptr);
272 op = {};
273 op.cancel_stream = true;
274 op.payload = &op_payload;
275 op_payload.cancel_stream.cancel_error = absl::CancelledError();
276 std::unique_ptr<TestClosure> next =
277 MakeTestClosure([&, s](grpc_error_handle /*error*/) {
278 if (!state.KeepRunning()) {
279 delete s;
280 return;
281 }
282 s->Init(state);
283 s->Op(&op);
284 s->DestroyThen(next.get());
285 });
286 grpc_core::Closure::Run(DEBUG_LOCATION, next.get(), absl::OkStatus());
287 f.FlushExecCtx();
288 }
289 BENCHMARK(BM_StreamCreateDestroy);
290
291 class RepresentativeClientInitialMetadata {
292 public:
293 static void Prepare(grpc_metadata_batch* b) {
294 b->Set(grpc_core::HttpSchemeMetadata(),
295 grpc_core::HttpSchemeMetadata::kHttp);
296 b->Set(grpc_core::HttpMethodMetadata(),
297 grpc_core::HttpMethodMetadata::kPost);
298 b->Set(grpc_core::HttpPathMetadata(),
299 grpc_core::Slice(grpc_core::StaticSlice::FromStaticString(
300 "/foo/bar/bm_chttp2_transport")));
301 b->Set(grpc_core::HttpAuthorityMetadata(),
302 grpc_core::Slice(grpc_core::StaticSlice::FromStaticString(
303 "foo.test.google.fr:1234")));
304 b->Set(
305 grpc_core::GrpcAcceptEncodingMetadata(),
306 grpc_core::CompressionAlgorithmSet(
307 {GRPC_COMPRESS_NONE, GRPC_COMPRESS_DEFLATE, GRPC_COMPRESS_GZIP}));
308 b->Set(grpc_core::TeMetadata(), grpc_core::TeMetadata::kTrailers);
309 b->Set(grpc_core::ContentTypeMetadata(),
310 grpc_core::ContentTypeMetadata::kApplicationGrpc);
311 b->Set(grpc_core::UserAgentMetadata(),
312 grpc_core::Slice(grpc_core::StaticSlice::FromStaticString(
313 "grpc-c/3.0.0-dev (linux; chttp2; green)")));
314 }
315 };
316
317 template <class Metadata>
318 static void BM_StreamCreateSendInitialMetadataDestroy(benchmark::State& state) {
319 grpc_core::ExecCtx exec_ctx;
320 Fixture f(grpc::ChannelArguments(), true);
321 auto* s = new Stream(&f);
322 grpc_transport_stream_op_batch op;
323 grpc_transport_stream_op_batch_payload op_payload(nullptr);
324 std::unique_ptr<TestClosure> start;
325 std::unique_ptr<TestClosure> done;
326
327 auto reset_op = [&]() {
328 op = {};
329 op.payload = &op_payload;
330 };
331
332 auto arena = grpc_core::MakeScopedArena(1024, g_memory_allocator);
333 grpc_metadata_batch b(arena.get());
334 Metadata::Prepare(&b);
335
336 f.FlushExecCtx();
337 gpr_event bm_done;
338 gpr_event_init(&bm_done);
339 start = MakeTestClosure([&, s](grpc_error_handle /*error*/) {
340 if (!state.KeepRunning()) {
341 delete s;
342 gpr_event_set(&bm_done, (void*)1);
343 return;
344 }
345 s->Init(state);
346 reset_op();
347 op.on_complete = done.get();
348 op.send_initial_metadata = true;
349 op.payload->send_initial_metadata.send_initial_metadata = &b;
350 s->Op(&op);
351 });
352 done = MakeTestClosure([&](grpc_error_handle /*error*/) {
353 reset_op();
354 op.cancel_stream = true;
355 op.payload->cancel_stream.cancel_error = absl::CancelledError();
356 s->Op(&op);
357 s->DestroyThen(start.get());
358 });
359 grpc_core::ExecCtx::Run(DEBUG_LOCATION, start.get(), absl::OkStatus());
360 f.FlushExecCtx();
361 gpr_event_wait(&bm_done, gpr_inf_future(GPR_CLOCK_REALTIME));
362 }
363 BENCHMARK_TEMPLATE(BM_StreamCreateSendInitialMetadataDestroy,
364 RepresentativeClientInitialMetadata);
365
366 static void BM_TransportEmptyOp(benchmark::State& state) {
367 grpc_core::ExecCtx exec_ctx;
368 Fixture f(grpc::ChannelArguments(), true);
369 auto* s = new Stream(&f);
370 s->Init(state);
371 grpc_transport_stream_op_batch op;
372 grpc_transport_stream_op_batch_payload op_payload(nullptr);
373 auto reset_op = [&]() {
374 op = {};
375 op.payload = &op_payload;
376 };
377 std::unique_ptr<TestClosure> c =
378 MakeTestClosure([&](grpc_error_handle /*error*/) {
379 if (!state.KeepRunning()) return;
380 reset_op();
381 op.on_complete = c.get();
382 s->Op(&op);
383 });
384 grpc_core::ExecCtx::Run(DEBUG_LOCATION, c.get(), absl::OkStatus());
385 f.FlushExecCtx();
386 reset_op();
387 op.cancel_stream = true;
388 op_payload.cancel_stream.cancel_error = absl::CancelledError();
389 gpr_event* stream_cancel_done = new gpr_event;
390 gpr_event_init(stream_cancel_done);
391 std::unique_ptr<TestClosure> stream_cancel_closure =
392 MakeTestClosure([&](grpc_error_handle error) {
393 GPR_ASSERT(error.ok());
394 gpr_event_set(stream_cancel_done, reinterpret_cast<void*>(1));
395 });
396 op.on_complete = stream_cancel_closure.get();
397 s->Op(&op);
398 f.FlushExecCtx();
399 gpr_event_wait(stream_cancel_done, gpr_inf_future(GPR_CLOCK_REALTIME));
400 done_events.emplace_back(stream_cancel_done);
401 s->DestroyThen(
402 MakeOnceClosure([s](grpc_error_handle /*error*/) { delete s; }));
403 f.FlushExecCtx();
404 }
405 BENCHMARK(BM_TransportEmptyOp);
406
407 // Some distros have RunSpecifiedBenchmarks under the benchmark namespace,
408 // and others do not. This allows us to support both modes.
409 namespace benchmark {
410 void RunTheBenchmarksNamespaced() { RunSpecifiedBenchmarks(); }
411 } // namespace benchmark
412
413 int main(int argc, char** argv) {
414 grpc::testing::TestEnvironment env(&argc, argv);
415 LibraryInitializer libInit;
416 ::benchmark::Initialize(&argc, argv);
417 grpc::testing::InitTest(&argc, &argv, false);
418 benchmark::RunTheBenchmarksNamespaced();
419 return 0;
420 }