Debian Codegraph @

src/cpp/server/load_reporter/load_reporter_async_service_impl.h

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 #ifndef GRPC_SRC_CPP_SERVER_LOAD_REPORTER_ASYNC_SERVICE_IMPL_H
20 #define GRPC_SRC_CPP_SERVER_LOAD_REPORTER_ASYNC_SERVICE_IMPL_H
21
22 #include <grpc/support/port_platform.h>
23
24 #include <stdint.h>
25
26 #include <atomic>
27 #include <functional>
28 #include <memory>
29 #include <string>
30 #include <utility>
31
32 #include <grpc/support/log.h>
33 #include <grpcpp/alarm.h>
34 #include <grpcpp/grpcpp.h>
35 #include <grpcpp/support/async_stream.h>
36 #include <grpcpp/support/interceptor.h>
37
38 #include "src/core/lib/gprpp/sync.h"
39 #include "src/core/lib/gprpp/thd.h"
40 #include "src/cpp/server/load_reporter/load_reporter.h"
41 #include "src/proto/grpc/lb/v1/load_reporter.grpc.pb.h"
42 #include "src/proto/grpc/lb/v1/load_reporter.pb.h"
43
44 namespace grpc {
45 namespace load_reporter {
46
47 // Async load reporting service. It's mainly responsible for controlling the
48 // procedure of incoming requests. The real business logic is handed off to the
49 // LoadReporter. There should be at most one instance of this service on a
50 // server to avoid spreading the load data into multiple places.
51 class LoadReporterAsyncServiceImpl
52 : public grpc::lb::v1::LoadReporter::AsyncService {
53 public:
54 explicit LoadReporterAsyncServiceImpl(
55 std::unique_ptr<ServerCompletionQueue> cq);
56 ~LoadReporterAsyncServiceImpl() override;
57
58 // Starts the working thread.
59 void StartThread();
60
61 // Not copyable nor movable.
62 LoadReporterAsyncServiceImpl(const LoadReporterAsyncServiceImpl&) = delete;
63 LoadReporterAsyncServiceImpl& operator=(const LoadReporterAsyncServiceImpl&) =
64 delete;
65
66 private:
67 class ReportLoadHandler;
68
69 // A tag that can be called with a bool argument. It's tailored for
70 // ReportLoadHandler's use. Before being used, it should be constructed with a
71 // method of ReportLoadHandler and a shared pointer to the handler. The
72 // shared pointer will be moved to the invoked function and the function can
73 // only be invoked once. That makes ref counting of the handler easier,
74 // because the shared pointer is not bound to the function and can be gone
75 // once the invoked function returns (if not used any more).
76 class CallableTag {
77 public:
78 using HandlerFunction =
79 std::function<void(std::shared_ptr<ReportLoadHandler>, bool)>;
80
81 CallableTag() {}
82
83 CallableTag(HandlerFunction func,
84 std::shared_ptr<ReportLoadHandler> handler)
85 : handler_function_(std::move(func)), handler_(std::move(handler)) {
86 GPR_ASSERT(handler_function_ != nullptr);
87 GPR_ASSERT(handler_ != nullptr);
88 }
89
90 // Runs the tag. This should be called only once. The handler is no longer
91 // owned by this tag after this method is invoked.
92 void Run(bool ok);
93
94 // Releases and returns the shared pointer to the handler.
95 std::shared_ptr<ReportLoadHandler> ReleaseHandler() {
96 return std::move(handler_);
97 }
98
99 private:
100 HandlerFunction handler_function_ = nullptr;
101 std::shared_ptr<ReportLoadHandler> handler_;
102 };
103
104 // Each handler takes care of one load reporting stream. It contains
105 // per-stream data and it will access the members of the parent class (i.e.,
106 // LoadReporterAsyncServiceImpl) for service-wide data (e.g., the load data).
107 class ReportLoadHandler {
108 public:
109 // Instantiates a ReportLoadHandler and requests the next load reporting
110 // call. The handler object will manage its own lifetime, so no action is
111 // needed from the caller any more regarding that object.
112 static void CreateAndStart(ServerCompletionQueue* cq,
113 LoadReporterAsyncServiceImpl* service,
114 LoadReporter* load_reporter);
115
116 // This ctor is public because we want to use std::make_shared<> in
117 // CreateAndStart(). This ctor shouldn't be used elsewhere.
118 ReportLoadHandler(ServerCompletionQueue* cq,
119 LoadReporterAsyncServiceImpl* service,
120 LoadReporter* load_reporter);
121
122 private:
123 // After the handler has a call request delivered, it starts reading the
124 // initial request. Also, a new handler is spawned so that we can keep
125 // servicing future calls.
126 void OnRequestDelivered(std::shared_ptr<ReportLoadHandler> self, bool ok);
127
128 // The first Read() is expected to succeed, after which the handler starts
129 // sending load reports back to the balancer. The second Read() is
130 // expected to fail, which happens when the balancer half-closes the
131 // stream to signal that it's no longer interested in the load reports. For
132 // the latter case, the handler will then close the stream.
133 void OnReadDone(std::shared_ptr<ReportLoadHandler> self, bool ok);
134
135 // The report sending operations are sequential as: send report -> send
136 // done, schedule the next send -> waiting for the alarm to fire -> alarm
137 // fires, send report -> ...
138 void SendReport(std::shared_ptr<ReportLoadHandler> self, bool ok);
139 void ScheduleNextReport(std::shared_ptr<ReportLoadHandler> self, bool ok);
140
141 // Called when Finish() is done.
142 void OnFinishDone(std::shared_ptr<ReportLoadHandler> self, bool ok);
143
144 // Called when AsyncNotifyWhenDone() notifies us.
145 void OnDoneNotified(std::shared_ptr<ReportLoadHandler> self, bool ok);
146
147 void Shutdown(std::shared_ptr<ReportLoadHandler> self, const char* reason);
148
149 // The key fields of the stream.
150 std::string lb_id_;
151 std::string load_balanced_hostname_;
152 std::string load_key_;
153 uint64_t load_report_interval_ms_;
154
155 // The data for RPC communication with the load reportee.
156 ServerContext ctx_;
157 grpc::lb::v1::LoadReportRequest request_;
158
159 // The members passed down from LoadReporterAsyncServiceImpl.
160 ServerCompletionQueue* cq_;
161 LoadReporterAsyncServiceImpl* service_;
162 LoadReporter* load_reporter_;
163 ServerAsyncReaderWriter<grpc::lb::v1::LoadReportResponse,
164 grpc::lb::v1::LoadReportRequest>
165 stream_;
166
167 // The status of the RPC progress.
168 enum CallStatus {
169 WAITING_FOR_DELIVERY,
170 DELIVERED,
171 INITIAL_REQUEST_RECEIVED,
172 INITIAL_RESPONSE_SENT,
173 FINISH_CALLED
174 } call_status_;
175 bool shutdown_{false};
176 bool done_notified_{false};
177 bool is_cancelled_{false};
178 CallableTag on_done_notified_;
179 CallableTag on_finish_done_;
180 CallableTag next_inbound_;
181 CallableTag next_outbound_;
182 std::unique_ptr<Alarm> next_report_alarm_;
183 };
184
185 // Handles the incoming requests and drives the completion queue in a loop.
186 static void Work(void* arg);
187
188 // Schedules the next data fetching from Census and LB feedback sampling.
189 void ScheduleNextFetchAndSample();
190
191 // Fetches data from Census and samples LB feedback.
192 void FetchAndSample(bool ok);
193
194 std::unique_ptr<ServerCompletionQueue> cq_;
195 // To synchronize the operations related to shutdown state of cq_, so that we
196 // don't enqueue new tags into cq_ after it is already shut down.
197 grpc_core::Mutex cq_shutdown_mu_;
198 std::atomic_bool shutdown_{false};
199 std::unique_ptr<grpc_core::Thread> thread_;
200 std::unique_ptr<LoadReporter> load_reporter_;
201 std::unique_ptr<Alarm> next_fetch_and_sample_alarm_;
202 };
203
204 } // namespace load_reporter
205 } // namespace grpc
206
207 #endif // GRPC_SRC_CPP_SERVER_LOAD_REPORTER_ASYNC_SERVICE_IMPL_H