Debian Codegraph @

test/core/transport/chttp2/flow_control_fuzzer.cc

raw
1 // Copyright 2022 gRPC authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #include <inttypes.h>
16 #include <stdio.h>
17 #include <stdlib.h>
18
19 #include <algorithm>
20 #include <deque>
21 #include <functional>
22 #include <limits>
23 #include <map>
24 #include <memory>
25 #include <queue>
26 #include <string>
27 #include <utility>
28 #include <vector>
29
30 #include "absl/base/attributes.h"
31 #include "absl/status/status.h"
32 #include "absl/types/optional.h"
33
34 #include <grpc/event_engine/memory_request.h>
35 #include <grpc/grpc.h>
36 #include <grpc/support/log.h>
37 #include <grpc/support/time.h>
38
39 #include "src/core/ext/transport/chttp2/transport/flow_control.h"
40 #include "src/core/lib/gpr/useful.h"
41 #include "src/core/lib/gprpp/time.h"
42 #include "src/core/lib/iomgr/exec_ctx.h"
43 #include "src/core/lib/resource_quota/memory_quota.h"
44 #include "src/core/lib/transport/bdp_estimator.h"
45 #include "src/libfuzzer/libfuzzer_macro.h"
46 #include "test/core/transport/chttp2/flow_control_fuzzer.pb.h"
47
48 // IWYU pragma: no_include <google/protobuf/repeated_ptr_field.h>
49
50 bool squelch = true;
51
52 extern gpr_timespec (*gpr_now_impl)(gpr_clock_type clock_type);
53
54 namespace grpc_core {
55 namespace chttp2 {
56 namespace {
57
58 constexpr uint64_t kMaxAdvanceTimeMillis = 24ull * 365 * 3600 * 1000;
59
60 gpr_timespec g_now;
61 gpr_timespec now_impl(gpr_clock_type clock_type) {
62 GPR_ASSERT(clock_type != GPR_TIMESPAN);
63 gpr_timespec ts = g_now;
64 ts.clock_type = clock_type;
65 return ts;
66 }
67
68 void InitGlobals() {
69 g_now = {1, 0, GPR_CLOCK_MONOTONIC};
70 TestOnlySetProcessEpoch(g_now);
71 gpr_now_impl = now_impl;
72 }
73
74 class FlowControlFuzzer {
75 public:
76 explicit FlowControlFuzzer(bool enable_bdp) {
77 ExecCtx exec_ctx;
78 tfc_ = std::make_unique<TransportFlowControl>("fuzzer", enable_bdp,
79 &memory_owner_);
80 }
81
82 ~FlowControlFuzzer() {
83 ExecCtx exec_ctx;
84 streams_.clear();
85 tfc_.reset();
86 memory_owner_.Release(allocated_memory_);
87 }
88
89 void Perform(const flow_control_fuzzer::Action& action);
90 void AssertNoneStuck() const;
91 void AssertAnnouncedOverInitialWindowSizeCorrect() const;
92
93 private:
94 struct StreamPayload {
95 uint32_t id;
96 uint64_t size;
97 };
98
99 struct SendToRemote {
100 bool bdp_ping = false;
101 absl::optional<uint32_t> initial_window_size;
102 uint32_t transport_window_update;
103 std::vector<StreamPayload> stream_window_updates;
104 };
105
106 struct SendFromRemote {
107 bool bdp_pong = false;
108 absl::optional<uint32_t> ack_initial_window_size;
109 std::vector<StreamPayload> stream_writes;
110 };
111
112 struct Stream {
113 explicit Stream(uint32_t id, TransportFlowControl* tfc) : id(id), fc(tfc) {}
114 uint32_t id;
115 StreamFlowControl fc;
116 int64_t queued_writes = 0;
117 int64_t window_delta = 0;
118 };
119
120 void PerformAction(FlowControlAction action, Stream* stream);
121 Stream* GetStream(uint32_t id) {
122 auto it = streams_.find(id);
123 if (it == streams_.end()) {
124 it = streams_.emplace(id, Stream{id, tfc_.get()}).first;
125 }
126 return &it->second;
127 }
128
129 MemoryQuotaRefPtr memory_quota_ = MakeMemoryQuota("fuzzer");
130 MemoryOwner memory_owner_ = memory_quota_->CreateMemoryOwner("owner");
131 std::unique_ptr<TransportFlowControl> tfc_;
132 absl::optional<uint32_t> queued_initial_window_size_;
133 absl::optional<uint32_t> queued_send_max_frame_size_;
134 bool scheduled_write_ = false;
135 bool sending_initial_window_size_ = false;
136 std::deque<SendToRemote> send_to_remote_;
137 std::deque<SendFromRemote> send_from_remote_;
138 uint32_t remote_initial_window_size_ = kDefaultWindow;
139 int64_t remote_transport_window_size_ = kDefaultWindow;
140 std::map<uint32_t, Stream> streams_;
141 std::queue<uint32_t> streams_to_update_;
142 uint64_t allocated_memory_ = 0;
143 Timestamp next_bdp_ping_ = Timestamp::ProcessEpoch();
144 };
145
146 void FlowControlFuzzer::Perform(const flow_control_fuzzer::Action& action) {
147 ExecCtx exec_ctx;
148 bool sending_payload = false;
149 switch (action.action_case()) {
150 case flow_control_fuzzer::Action::ACTION_NOT_SET:
151 break;
152 case flow_control_fuzzer::Action::kSetMemoryQuota: {
153 memory_quota_->SetSize(
154 Clamp(action.set_memory_quota(), uint64_t(1),
155 uint64_t(std::numeric_limits<int64_t>::max())));
156 } break;
157 case flow_control_fuzzer::Action::kStepTimeMs: {
158 g_now = gpr_time_add(
159 g_now, gpr_time_from_millis(Clamp(action.step_time_ms(), uint64_t(1),
160 kMaxAdvanceTimeMillis),
161 GPR_TIMESPAN));
162 exec_ctx.InvalidateNow();
163 if (Timestamp::Now() >= next_bdp_ping_) {
164 scheduled_write_ = true;
165 }
166 } break;
167 case flow_control_fuzzer::Action::kPeriodicUpdate: {
168 PerformAction(tfc_->PeriodicUpdate(), nullptr);
169 } break;
170 case flow_control_fuzzer::Action::kPerformSendToRemote: {
171 scheduled_write_ = true;
172 } break;
173 case flow_control_fuzzer::Action::kPerformSendToRemoteWithPayload: {
174 scheduled_write_ = true;
175 sending_payload = true;
176 } break;
177 case flow_control_fuzzer::Action::kReadSendToRemote: {
178 if (send_to_remote_.empty()) break;
179 auto sent_to_remote = send_to_remote_.front();
180 if (sent_to_remote.initial_window_size.has_value()) {
181 if (!squelch) {
182 fprintf(stderr, "Setting initial window size to %d\n",
183 sent_to_remote.initial_window_size.value());
184 }
185 SendFromRemote send_from_remote;
186 send_from_remote.ack_initial_window_size =
187 sent_to_remote.initial_window_size;
188 for (const auto& id_stream : streams_) {
189 GPR_ASSERT(id_stream.second.window_delta +
190 *sent_to_remote.initial_window_size <=
191 (1u << 31) - 1);
192 }
193 remote_initial_window_size_ = *sent_to_remote.initial_window_size;
194 send_from_remote_.push_back(send_from_remote);
195 }
196 if (sent_to_remote.bdp_ping) {
197 SendFromRemote send_from_remote;
198 send_from_remote.bdp_pong = true;
199 send_from_remote_.push_back(send_from_remote);
200 }
201 for (auto stream_update : sent_to_remote.stream_window_updates) {
202 Stream* s = GetStream(stream_update.id);
203 if (!squelch) {
204 fprintf(stderr,
205 "[%" PRIu32 "]: increase window delta by %" PRIu64
206 " from %" PRId64 "\n",
207 stream_update.id, stream_update.size, s->window_delta);
208 }
209 s->window_delta += stream_update.size;
210 GPR_ASSERT(s->window_delta <= chttp2::kMaxWindowDelta);
211 }
212 remote_transport_window_size_ += sent_to_remote.transport_window_update;
213 send_to_remote_.pop_front();
214 } break;
215 case flow_control_fuzzer::Action::kReadSendFromRemote: {
216 if (send_from_remote_.empty()) break;
217 auto sent_from_remote = send_from_remote_.front();
218 if (sent_from_remote.ack_initial_window_size.has_value()) {
219 if (!squelch) {
220 fprintf(stderr, "Received ACK for initial window size %d\n",
221 *sent_from_remote.ack_initial_window_size);
222 }
223 tfc_->SetAckedInitialWindow(*sent_from_remote.ack_initial_window_size);
224 sending_initial_window_size_ = false;
225 }
226 if (sent_from_remote.bdp_pong) {
227 next_bdp_ping_ = tfc_->bdp_estimator()->CompletePing();
228 }
229 for (const auto& stream_write : sent_from_remote.stream_writes) {
230 Stream* stream = GetStream(stream_write.id);
231 if (!squelch) {
232 fprintf(stderr, "[%" PRIu32 "]: recv write of %" PRIu64 "\n",
233 stream_write.id, stream_write.size);
234 }
235 if (auto* bdp = tfc_->bdp_estimator()) {
236 bdp->AddIncomingBytes(stream_write.size);
237 }
238 StreamFlowControl::IncomingUpdateContext upd(&stream->fc);
239 GPR_ASSERT(upd.RecvData(stream_write.size).ok());
240 PerformAction(upd.MakeAction(), stream);
241 }
242 send_from_remote_.pop_front();
243 } break;
244 case flow_control_fuzzer::Action::kStreamWrite: {
245 Stream* s = GetStream(action.stream_write().id());
246 s->queued_writes += action.stream_write().size();
247 } break;
248 case flow_control_fuzzer::Action::kPerformSendFromRemote: {
249 SendFromRemote send;
250 for (auto& id_stream : streams_) {
251 auto send_amount = std::min(
252 {id_stream.second.queued_writes, remote_transport_window_size_,
253 remote_initial_window_size_ + id_stream.second.window_delta});
254 if (send_amount <= 0) continue;
255 send.stream_writes.push_back({id_stream.first, uint64_t(send_amount)});
256 id_stream.second.queued_writes -= send_amount;
257 id_stream.second.window_delta -= send_amount;
258 remote_transport_window_size_ -= send_amount;
259 }
260 send_from_remote_.push_back(send);
261 } break;
262 case flow_control_fuzzer::Action::kSetMinProgressSize: {
263 Stream* s = GetStream(action.set_min_progress_size().id());
264 StreamFlowControl::IncomingUpdateContext upd(&s->fc);
265 upd.SetMinProgressSize(action.set_min_progress_size().size());
266 PerformAction(upd.MakeAction(), s);
267 } break;
268 case flow_control_fuzzer::Action::kAllocateMemory: {
269 auto allocate = std::min(
270 size_t(action.allocate_memory()),
271 grpc_event_engine::experimental::MemoryRequest::max_allowed_size());
272 allocated_memory_ += allocate;
273 memory_owner_.Reserve(allocate);
274 } break;
275 case flow_control_fuzzer::Action::kDeallocateMemory: {
276 auto deallocate =
277 std::min(uint64_t(action.deallocate_memory()), allocated_memory_);
278 allocated_memory_ -= deallocate;
279 memory_owner_.Release(deallocate);
280 } break;
281 case flow_control_fuzzer::Action::kSetPendingSize: {
282 Stream* s = GetStream(action.set_min_progress_size().id());
283 StreamFlowControl::IncomingUpdateContext upd(&s->fc);
284 upd.SetPendingSize(action.set_pending_size().size());
285 PerformAction(upd.MakeAction(), s);
286 } break;
287 }
288 if (scheduled_write_) {
289 SendToRemote send;
290 if (Timestamp::Now() >= next_bdp_ping_) {
291 if (auto* bdp = tfc_->bdp_estimator()) {
292 bdp->SchedulePing();
293 bdp->StartPing();
294 next_bdp_ping_ = Timestamp::InfFuture();
295 send.bdp_ping = true;
296 }
297 }
298 if (!sending_initial_window_size_ &&
299 queued_initial_window_size_.has_value()) {
300 sending_initial_window_size_ = true;
301 send.initial_window_size =
302 std::exchange(queued_initial_window_size_, absl::nullopt);
303 }
304 while (!streams_to_update_.empty()) {
305 auto* stream = GetStream(streams_to_update_.front());
306 streams_to_update_.pop();
307 send.stream_window_updates.push_back(
308 {stream->id, stream->fc.MaybeSendUpdate()});
309 }
310 send.transport_window_update = tfc_->MaybeSendUpdate(sending_payload);
311 queued_send_max_frame_size_.reset();
312 send_to_remote_.emplace_back(std::move(send));
313 scheduled_write_ = false;
314 }
315 }
316
317 void FlowControlFuzzer::PerformAction(FlowControlAction action,
318 Stream* stream) {
319 if (!squelch) {
320 fprintf(stderr, "[%" PRId64 "]: ACTION: %s\n",
321 stream == nullptr ? int64_t(-1) : int64_t(stream->id),
322 action.DebugString().c_str());
323 }
324
325 auto with_urgency = [this](FlowControlAction::Urgency urgency,
326 std::function<void()> f) {
327 switch (urgency) {
328 case FlowControlAction::Urgency::NO_ACTION_NEEDED:
329 break;
330 case FlowControlAction::Urgency::UPDATE_IMMEDIATELY:
331 scheduled_write_ = true;
332 ABSL_FALLTHROUGH_INTENDED;
333 case FlowControlAction::Urgency::QUEUE_UPDATE:
334 f();
335 break;
336 }
337 };
338 with_urgency(action.send_stream_update(),
339 [this, stream]() { streams_to_update_.push(stream->id); });
340 with_urgency(action.send_transport_update(), []() {});
341 with_urgency(action.send_initial_window_update(), [this, &action]() {
342 GPR_ASSERT(action.initial_window_size() <= chttp2::kMaxInitialWindowSize);
343 queued_initial_window_size_ = action.initial_window_size();
344 });
345 with_urgency(action.send_max_frame_size_update(), [this, &action]() {
346 queued_send_max_frame_size_ = action.max_frame_size();
347 });
348 }
349
350 void FlowControlFuzzer::AssertNoneStuck() const {
351 GPR_ASSERT(!scheduled_write_);
352
353 // Reconcile all the values to get the view of the remote that is knowable to
354 // the flow control system.
355 std::map<uint32_t, int64_t> reconciled_stream_deltas;
356 int64_t reconciled_transport_window = remote_transport_window_size_;
357 int64_t reconciled_initial_window = remote_initial_window_size_;
358 for (const auto& id_stream : streams_) {
359 reconciled_stream_deltas[id_stream.first] = id_stream.second.window_delta;
360 }
361
362 // Anything that's been sent from flow control -> remote needs to be added to
363 // the remote.
364 for (const auto& send_to_remote : send_to_remote_) {
365 if (send_to_remote.initial_window_size.has_value()) {
366 reconciled_initial_window = *send_to_remote.initial_window_size;
367 }
368 reconciled_transport_window += send_to_remote.transport_window_update;
369 for (const auto& stream_update : send_to_remote.stream_window_updates) {
370 reconciled_stream_deltas[stream_update.id] += stream_update.size;
371 }
372 }
373
374 // Anything that's been sent from remote -> flow control needs to be wound
375 // back into the remote.
376 for (const auto& send_from_remote : send_from_remote_) {
377 for (const auto& stream_write : send_from_remote.stream_writes) {
378 reconciled_stream_deltas[stream_write.id] += stream_write.size;
379 reconciled_transport_window += stream_write.size;
380 }
381 }
382
383 // Finally, if a stream has indicated it's willing to read, the reconciled
384 // remote *MUST* be in a state where it could send at least one byte.
385 for (const auto& id_stream : streams_) {
386 if (id_stream.second.fc.min_progress_size() == 0) continue;
387 int64_t stream_window =
388 reconciled_stream_deltas[id_stream.first] + reconciled_initial_window;
389 if (stream_window <= 0 || reconciled_transport_window <= 0) {
390 fprintf(stderr,
391 "FAILED: stream %d has stream_window=%" PRId64
392 ", transport_window=%" PRId64 ", delta=%" PRId64
393 ", init_window_size=%" PRId64 ", min_progress_size=%" PRId64 "\n",
394 id_stream.first, stream_window, reconciled_transport_window,
395 reconciled_stream_deltas[id_stream.first],
396 reconciled_initial_window,
397 int64_t(id_stream.second.fc.min_progress_size()));
398 abort();
399 }
400 }
401 }
402
403 void FlowControlFuzzer::AssertAnnouncedOverInitialWindowSizeCorrect() const {
404 int64_t value_from_streams = 0;
405
406 for (const auto& id_stream : streams_) {
407 const auto& stream = id_stream.second;
408 if (stream.fc.announced_window_delta() > 0) {
409 value_from_streams += stream.fc.announced_window_delta();
410 }
411 }
412
413 GPR_ASSERT(value_from_streams ==
414 tfc_->announced_stream_total_over_incoming_window());
415 }
416
417 } // namespace
418 } // namespace chttp2
419 } // namespace grpc_core
420
421 DEFINE_PROTO_FUZZER(const flow_control_fuzzer::Msg& msg) {
422 grpc_core::chttp2::InitGlobals();
423 grpc_core::chttp2::FlowControlFuzzer fuzzer(msg.enable_bdp());
424 for (const auto& action : msg.actions()) {
425 if (!squelch) {
426 fprintf(stderr, "%s\n", action.DebugString().c_str());
427 }
428 fuzzer.Perform(action);
429 fuzzer.AssertNoneStuck();
430 fuzzer.AssertAnnouncedOverInitialWindowSizeCorrect();
431 }
432 }