Debian Codegraph @

src/cpp/server/load_reporter/load_reporter_async_service_impl.cc

raw
1 /*
2 *
3 * Copyright 2018 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 #include <grpc/support/port_platform.h>
20
21 #include "src/cpp/server/load_reporter/load_reporter_async_service_impl.h"
22
23 #include <inttypes.h>
24
25 #include <google/protobuf/duration.pb.h>
26 #include <google/protobuf/repeated_ptr_field.h>
27
28 #include <grpc/impl/codegen/gpr_types.h>
29 #include <grpc/support/time.h>
30 #include <grpcpp/support/status.h>
31
32 #include "src/cpp/server/load_reporter/constants.h"
33
34 namespace grpc {
35 namespace load_reporter {
36
37 void LoadReporterAsyncServiceImpl::CallableTag::Run(bool ok) {
38 GPR_ASSERT(handler_function_ != nullptr);
39 GPR_ASSERT(handler_ != nullptr);
40 handler_function_(std::move(handler_), ok);
41 }
42
43 LoadReporterAsyncServiceImpl::LoadReporterAsyncServiceImpl(
44 std::unique_ptr<ServerCompletionQueue> cq)
45 : cq_(std::move(cq)) {
46 thread_ =
47 std::make_unique<grpc_core::Thread>("server_load_reporting", Work, this);
48 std::unique_ptr<CpuStatsProvider> cpu_stats_provider = nullptr;
49 #if defined(GPR_LINUX) || defined(GPR_WINDOWS) || defined(GPR_APPLE)
50 cpu_stats_provider = std::make_unique<CpuStatsProviderDefaultImpl>();
51 #endif
52 load_reporter_ = std::make_unique<LoadReporter>(
53 kFeedbackSampleWindowSeconds,
54 std::unique_ptr<CensusViewProvider>(new CensusViewProviderDefaultImpl()),
55 std::move(cpu_stats_provider));
56 }
57
58 LoadReporterAsyncServiceImpl::~LoadReporterAsyncServiceImpl() {
59 // We will reach here after the server starts shutting down.
60 shutdown_ = true;
61 {
62 grpc_core::MutexLock lock(&cq_shutdown_mu_);
63 cq_->Shutdown();
64 }
65 if (next_fetch_and_sample_alarm_ != nullptr) {
66 next_fetch_and_sample_alarm_->Cancel();
67 }
68 thread_->Join();
69 }
70
71 void LoadReporterAsyncServiceImpl::ScheduleNextFetchAndSample() {
72 auto next_fetch_and_sample_time =
73 gpr_time_add(gpr_now(GPR_CLOCK_MONOTONIC),
74 gpr_time_from_millis(kFetchAndSampleIntervalSeconds * 1000,
75 GPR_TIMESPAN));
76 {
77 grpc_core::MutexLock lock(&cq_shutdown_mu_);
78 if (shutdown_) return;
79 // TODO(juanlishen): Improve the Alarm implementation to reuse a single
80 // instance for multiple events.
81 next_fetch_and_sample_alarm_ = std::make_unique<Alarm>();
82 next_fetch_and_sample_alarm_->Set(cq_.get(), next_fetch_and_sample_time,
83 this);
84 }
85 gpr_log(GPR_DEBUG, "[LRS %p] Next fetch-and-sample scheduled.", this);
86 }
87
88 void LoadReporterAsyncServiceImpl::FetchAndSample(bool ok) {
89 if (!ok) {
90 gpr_log(GPR_INFO, "[LRS %p] Fetch-and-sample is stopped.", this);
91 return;
92 }
93 gpr_log(GPR_DEBUG, "[LRS %p] Starting a fetch-and-sample...", this);
94 load_reporter_->FetchAndSample();
95 ScheduleNextFetchAndSample();
96 }
97
98 void LoadReporterAsyncServiceImpl::Work(void* arg) {
99 LoadReporterAsyncServiceImpl* service =
100 static_cast<LoadReporterAsyncServiceImpl*>(arg);
101 service->FetchAndSample(true /* ok */);
102 // TODO(juanlishen): This is a workaround to wait for the cq to be ready. Need
103 // to figure out why cq is not ready after service starts.
104 gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_MONOTONIC),
105 gpr_time_from_seconds(1, GPR_TIMESPAN)));
106 ReportLoadHandler::CreateAndStart(service->cq_.get(), service,
107 service->load_reporter_.get());
108 void* tag;
109 bool ok;
110 while (true) {
111 if (!service->cq_->Next(&tag, &ok)) {
112 // The completion queue is shutting down.
113 GPR_ASSERT(service->shutdown_);
114 break;
115 }
116 if (tag == service) {
117 service->FetchAndSample(ok);
118 } else {
119 auto* next_step = static_cast<CallableTag*>(tag);
120 next_step->Run(ok);
121 }
122 }
123 }
124
125 void LoadReporterAsyncServiceImpl::StartThread() { thread_->Start(); }
126
127 void LoadReporterAsyncServiceImpl::ReportLoadHandler::CreateAndStart(
128 ServerCompletionQueue* cq, LoadReporterAsyncServiceImpl* service,
129 LoadReporter* load_reporter) {
130 std::shared_ptr<ReportLoadHandler> handler =
131 std::make_shared<ReportLoadHandler>(cq, service, load_reporter);
132 ReportLoadHandler* p = handler.get();
133 {
134 grpc_core::MutexLock lock(&service->cq_shutdown_mu_);
135 if (service->shutdown_) return;
136 p->on_done_notified_ =
137 CallableTag(std::bind(&ReportLoadHandler::OnDoneNotified, p,
138 std::placeholders::_1, std::placeholders::_2),
139 handler);
140 p->next_inbound_ =
141 CallableTag(std::bind(&ReportLoadHandler::OnRequestDelivered, p,
142 std::placeholders::_1, std::placeholders::_2),
143 std::move(handler));
144 p->ctx_.AsyncNotifyWhenDone(&p->on_done_notified_);
145 service->RequestReportLoad(&p->ctx_, &p->stream_, cq, cq,
146 &p->next_inbound_);
147 }
148 }
149
150 LoadReporterAsyncServiceImpl::ReportLoadHandler::ReportLoadHandler(
151 ServerCompletionQueue* cq, LoadReporterAsyncServiceImpl* service,
152 LoadReporter* load_reporter)
153 : cq_(cq),
154 service_(service),
155 load_reporter_(load_reporter),
156 stream_(&ctx_),
157 call_status_(WAITING_FOR_DELIVERY) {}
158
159 void LoadReporterAsyncServiceImpl::ReportLoadHandler::OnRequestDelivered(
160 std::shared_ptr<ReportLoadHandler> self, bool ok) {
161 if (ok) {
162 call_status_ = DELIVERED;
163 } else {
164 // AsyncNotifyWhenDone() needs to be called before the call starts, but the
165 // tag will not pop out if the call never starts (
166 // https://github.com/grpc/grpc/issues/10136). So we need to manually
167 // release the ownership of the handler in this case.
168 GPR_ASSERT(on_done_notified_.ReleaseHandler() != nullptr);
169 }
170 if (!ok || shutdown_) {
171 // The value of ok being false means that the server is shutting down.
172 Shutdown(std::move(self), "OnRequestDelivered");
173 return;
174 }
175 // Spawn a new handler instance to serve the next new client. Every handler
176 // instance will deallocate itself when it's done.
177 CreateAndStart(cq_, service_, load_reporter_);
178 {
179 grpc_core::ReleasableMutexLock lock(&service_->cq_shutdown_mu_);
180 if (service_->shutdown_) {
181 lock.Release();
182 Shutdown(std::move(self), "OnRequestDelivered");
183 return;
184 }
185 next_inbound_ =
186 CallableTag(std::bind(&ReportLoadHandler::OnReadDone, this,
187 std::placeholders::_1, std::placeholders::_2),
188 std::move(self));
189 stream_.Read(&request_, &next_inbound_);
190 }
191 // LB ID is unique for each load reporting stream.
192 lb_id_ = load_reporter_->GenerateLbId();
193 gpr_log(GPR_INFO,
194 "[LRS %p] Call request delivered (lb_id_: %s, handler: %p). "
195 "Start reading the initial request...",
196 service_, lb_id_.c_str(), this);
197 }
198
199 void LoadReporterAsyncServiceImpl::ReportLoadHandler::OnReadDone(
200 std::shared_ptr<ReportLoadHandler> self, bool ok) {
201 if (!ok || shutdown_) {
202 if (!ok && call_status_ < INITIAL_REQUEST_RECEIVED) {
203 // The client may have half-closed the stream or the stream is broken.
204 gpr_log(GPR_INFO,
205 "[LRS %p] Failed reading the initial request from the stream "
206 "(lb_id_: %s, handler: %p, done_notified: %d, is_cancelled: %d).",
207 service_, lb_id_.c_str(), this, static_cast<int>(done_notified_),
208 static_cast<int>(is_cancelled_));
209 }
210 Shutdown(std::move(self), "OnReadDone");
211 return;
212 }
213 // We only receive one request, which is the initial request.
214 if (call_status_ < INITIAL_REQUEST_RECEIVED) {
215 if (!request_.has_initial_request()) {
216 Shutdown(std::move(self), "OnReadDone+initial_request_not_found");
217 } else {
218 call_status_ = INITIAL_REQUEST_RECEIVED;
219 const auto& initial_request = request_.initial_request();
220 load_balanced_hostname_ = initial_request.load_balanced_hostname();
221 load_key_ = initial_request.load_key();
222 load_reporter_->ReportStreamCreated(load_balanced_hostname_, lb_id_,
223 load_key_);
224 const auto& load_report_interval = initial_request.load_report_interval();
225 load_report_interval_ms_ =
226 static_cast<unsigned long>(load_report_interval.seconds() * 1000 +
227 load_report_interval.nanos() / 1000);
228 gpr_log(GPR_INFO,
229 "[LRS %p] Initial request received. Start load reporting (load "
230 "balanced host: %s, interval: %" PRIu64
231 " ms, lb_id_: %s, handler: %p)...",
232 service_, load_balanced_hostname_.c_str(),
233 load_report_interval_ms_, lb_id_.c_str(), this);
234 SendReport(self, true /* ok */);
235 // Expect this read to fail.
236 {
237 grpc_core::ReleasableMutexLock lock(&service_->cq_shutdown_mu_);
238 if (service_->shutdown_) {
239 lock.Release();
240 Shutdown(std::move(self), "OnReadDone");
241 return;
242 }
243 next_inbound_ =
244 CallableTag(std::bind(&ReportLoadHandler::OnReadDone, this,
245 std::placeholders::_1, std::placeholders::_2),
246 std::move(self));
247 stream_.Read(&request_, &next_inbound_);
248 }
249 }
250 } else {
251 // Another request received! This violates the spec.
252 gpr_log(GPR_ERROR,
253 "[LRS %p] Another request received (lb_id_: %s, handler: %p).",
254 service_, lb_id_.c_str(), this);
255 Shutdown(std::move(self), "OnReadDone+second_request");
256 }
257 }
258
259 void LoadReporterAsyncServiceImpl::ReportLoadHandler::ScheduleNextReport(
260 std::shared_ptr<ReportLoadHandler> self, bool ok) {
261 if (!ok || shutdown_) {
262 Shutdown(std::move(self), "ScheduleNextReport");
263 return;
264 }
265 auto next_report_time = gpr_time_add(
266 gpr_now(GPR_CLOCK_MONOTONIC),
267 gpr_time_from_millis(load_report_interval_ms_, GPR_TIMESPAN));
268 {
269 grpc_core::ReleasableMutexLock lock(&service_->cq_shutdown_mu_);
270 if (service_->shutdown_) {
271 lock.Release();
272 Shutdown(std::move(self), "ScheduleNextReport");
273 return;
274 }
275 next_outbound_ =
276 CallableTag(std::bind(&ReportLoadHandler::SendReport, this,
277 std::placeholders::_1, std::placeholders::_2),
278 std::move(self));
279 // TODO(juanlishen): Improve the Alarm implementation to reuse a single
280 // instance for multiple events.
281 next_report_alarm_ = std::make_unique<Alarm>();
282 next_report_alarm_->Set(cq_, next_report_time, &next_outbound_);
283 }
284 gpr_log(GPR_DEBUG,
285 "[LRS %p] Next load report scheduled (lb_id_: %s, handler: %p).",
286 service_, lb_id_.c_str(), this);
287 }
288
289 void LoadReporterAsyncServiceImpl::ReportLoadHandler::SendReport(
290 std::shared_ptr<ReportLoadHandler> self, bool ok) {
291 if (!ok || shutdown_) {
292 Shutdown(std::move(self), "SendReport");
293 return;
294 }
295 grpc::lb::v1::LoadReportResponse response;
296 auto loads = load_reporter_->GenerateLoads(load_balanced_hostname_, lb_id_);
297 response.mutable_load()->Swap(&loads);
298 auto feedback = load_reporter_->GenerateLoadBalancingFeedback();
299 response.mutable_load_balancing_feedback()->Swap(&feedback);
300 if (call_status_ < INITIAL_RESPONSE_SENT) {
301 auto initial_response = response.mutable_initial_response();
302 initial_response->set_load_balancer_id(lb_id_);
303 initial_response->set_implementation_id(
304 grpc::lb::v1::InitialLoadReportResponse::CPP);
305 initial_response->set_server_version(kVersion);
306 call_status_ = INITIAL_RESPONSE_SENT;
307 }
308 {
309 grpc_core::ReleasableMutexLock lock(&service_->cq_shutdown_mu_);
310 if (service_->shutdown_) {
311 lock.Release();
312 Shutdown(std::move(self), "SendReport");
313 return;
314 }
315 next_outbound_ =
316 CallableTag(std::bind(&ReportLoadHandler::ScheduleNextReport, this,
317 std::placeholders::_1, std::placeholders::_2),
318 std::move(self));
319 stream_.Write(response, &next_outbound_);
320 gpr_log(GPR_INFO,
321 "[LRS %p] Sending load report (lb_id_: %s, handler: %p, loads "
322 "count: %d)...",
323 service_, lb_id_.c_str(), this, response.load().size());
324 }
325 }
326
327 void LoadReporterAsyncServiceImpl::ReportLoadHandler::OnDoneNotified(
328 std::shared_ptr<ReportLoadHandler> self, bool ok) {
329 GPR_ASSERT(ok);
330 done_notified_ = true;
331 if (ctx_.IsCancelled()) {
332 is_cancelled_ = true;
333 }
334 gpr_log(GPR_INFO,
335 "[LRS %p] Load reporting call is notified done (handler: %p, "
336 "is_cancelled: %d).",
337 service_, this, static_cast<int>(is_cancelled_));
338 Shutdown(std::move(self), "OnDoneNotified");
339 }
340
341 void LoadReporterAsyncServiceImpl::ReportLoadHandler::Shutdown(
342 std::shared_ptr<ReportLoadHandler> self, const char* reason) {
343 if (!shutdown_) {
344 gpr_log(GPR_INFO,
345 "[LRS %p] Shutting down the handler (lb_id_: %s, handler: %p, "
346 "reason: %s).",
347 service_, lb_id_.c_str(), this, reason);
348 shutdown_ = true;
349 if (call_status_ >= INITIAL_REQUEST_RECEIVED) {
350 load_reporter_->ReportStreamClosed(load_balanced_hostname_, lb_id_);
351 next_report_alarm_->Cancel();
352 }
353 }
354 // OnRequestDelivered() may be called after OnDoneNotified(), so we need to
355 // try to Finish() every time we are in Shutdown().
356 if (call_status_ >= DELIVERED && call_status_ < FINISH_CALLED) {
357 grpc_core::MutexLock lock(&service_->cq_shutdown_mu_);
358 if (!service_->shutdown_) {
359 on_finish_done_ =
360 CallableTag(std::bind(&ReportLoadHandler::OnFinishDone, this,
361 std::placeholders::_1, std::placeholders::_2),
362 std::move(self));
363 // TODO(juanlishen): Maybe add a message proto for the client to
364 // explicitly cancel the stream so that we can return OK status in such
365 // cases.
366 stream_.Finish(Status::CANCELLED, &on_finish_done_);
367 call_status_ = FINISH_CALLED;
368 }
369 }
370 }
371
372 void LoadReporterAsyncServiceImpl::ReportLoadHandler::OnFinishDone(
373 // NOLINTNEXTLINE(performance-unnecessary-value-param)
374 std::shared_ptr<ReportLoadHandler> /*self*/, bool ok) {
375 if (ok) {
376 gpr_log(GPR_INFO,
377 "[LRS %p] Load reporting finished (lb_id_: %s, handler: %p).",
378 service_, lb_id_.c_str(), this);
379 }
380 }
381
382 } // namespace load_reporter
383 } // namespace grpc