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
|
#include "grpc_server.h"
#include <util/string/join.h>
#include <util/generic/yexception.h>
#include <util/system/thread.h>
#include <util/generic/map.h>
#include <grpc++/resource_quota.h>
#include <contrib/libs/grpc/src/core/lib/iomgr/socket_mutator.h>
#if !defined(_WIN32) && !defined(_WIN64)
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#endif
namespace NGrpc {
using NThreading::TFuture;
static void PullEvents(grpc::ServerCompletionQueue* cq) {
TThread::SetCurrentThreadName("grpc_server");
while (true) {
void* tag; // uniquely identifies a request.
bool ok;
if (cq->Next(&tag, &ok)) {
IQueueEvent* const ev(static_cast<IQueueEvent*>(tag));
if (!ev->Execute(ok)) {
ev->DestroyRequest();
}
} else {
break;
}
}
}
TGRpcServer::TGRpcServer(const TServerOptions& opts)
: Options_(opts)
, Limiter_(Options_.MaxGlobalRequestInFlight)
{}
TGRpcServer::~TGRpcServer() {
Y_ABORT_UNLESS(Ts.empty());
Services_.clear();
}
void TGRpcServer::AddService(IGRpcServicePtr service) {
Services_.push_back(service);
}
void TGRpcServer::Start() {
TString server_address(Join(":", Options_.Host, Options_.Port)); // https://st.yandex-team.ru/DTCC-695
using grpc::ServerBuilder;
using grpc::ResourceQuota;
ServerBuilder builder;
auto credentials = grpc::InsecureServerCredentials();
if (Options_.SslData) {
grpc::SslServerCredentialsOptions::PemKeyCertPair keycert;
keycert.cert_chain = std::move(Options_.SslData->Cert);
keycert.private_key = std::move(Options_.SslData->Key);
grpc::SslServerCredentialsOptions sslOps;
sslOps.pem_root_certs = std::move(Options_.SslData->Root);
sslOps.pem_key_cert_pairs.push_back(keycert);
if (Options_.SslData->DoRequestClientCertificate) {
sslOps.client_certificate_request = GRPC_SSL_REQUEST_CLIENT_CERTIFICATE_AND_VERIFY;
}
credentials = grpc::SslServerCredentials(sslOps);
}
if (Options_.ExternalListener) {
Options_.ExternalListener->Init(builder.experimental().AddExternalConnectionAcceptor(
ServerBuilder::experimental_type::ExternalConnectionType::FROM_FD,
credentials
));
} else {
builder.AddListeningPort(server_address, credentials);
}
builder.SetMaxReceiveMessageSize(Options_.MaxMessageSize);
builder.SetMaxSendMessageSize(Options_.MaxMessageSize);
for (IGRpcServicePtr service : Services_) {
service->SetServerOptions(Options_);
builder.RegisterService(service->GetService());
service->SetGlobalLimiterHandle(&Limiter_);
}
class TKeepAliveOption: public grpc::ServerBuilderOption {
public:
TKeepAliveOption(int idle, int interval)
: Idle(idle)
, Interval(interval)
, KeepAliveEnabled(true)
{}
TKeepAliveOption()
: Idle(0)
, Interval(0)
, KeepAliveEnabled(false)
{}
void UpdateArguments(grpc::ChannelArguments *args) override {
args->SetInt(GRPC_ARG_HTTP2_MAX_PING_STRIKES, 0);
args->SetInt(GRPC_ARG_HTTP2_MIN_RECV_PING_INTERVAL_WITHOUT_DATA_MS, 1000);
if (KeepAliveEnabled) {
args->SetInt(GRPC_ARG_HTTP2_MAX_PINGS_WITHOUT_DATA, 0);
args->SetInt(GRPC_ARG_KEEPALIVE_PERMIT_WITHOUT_CALLS, 1);
args->SetInt(GRPC_ARG_HTTP2_MIN_SENT_PING_INTERVAL_WITHOUT_DATA_MS, Idle * 1000);
args->SetInt(GRPC_ARG_KEEPALIVE_TIME_MS, Idle * 1000);
args->SetInt(GRPC_ARG_KEEPALIVE_TIMEOUT_MS, Interval * 1000);
}
}
void UpdatePlugins(std::vector<std::unique_ptr<grpc::ServerBuilderPlugin>>* /*plugins*/) override
{}
private:
const int Idle;
const int Interval;
const bool KeepAliveEnabled;
};
if (Options_.KeepAliveEnable) {
builder.SetOption(std::make_unique<TKeepAliveOption>(
Options_.KeepAliveIdleTimeoutTriggerSec,
Options_.KeepAliveProbeIntervalSec));
} else {
builder.SetOption(std::make_unique<TKeepAliveOption>());
}
size_t completionQueueCount = 1;
if (Options_.WorkersPerCompletionQueue) {
size_t threadsPerQueue = Max(std::size_t{1}, Options_.WorkersPerCompletionQueue);
completionQueueCount = (Options_.WorkerThreads + threadsPerQueue - 1) / threadsPerQueue; // ceiling
} else if (Options_.UseCompletionQueuePerThread) {
completionQueueCount = Options_.WorkerThreads;
}
CQS_.reserve(completionQueueCount);
for (size_t i = 0; i < completionQueueCount; ++i) {
CQS_.push_back(builder.AddCompletionQueue());
}
if (Options_.GRpcMemoryQuotaBytes) {
// See details KIKIMR-6932
if (Options_.EnableGRpcMemoryQuota) {
grpc::ResourceQuota quota("memory_bound");
quota.Resize(Options_.GRpcMemoryQuotaBytes);
builder.SetResourceQuota(quota);
Cerr << "Set GRpc memory quota to: " << Options_.GRpcMemoryQuotaBytes << Endl;
} else {
Cerr << "GRpc memory quota was set but disabled due to issues with grpc quoter"
", to enable it use EnableGRpcMemoryQuota option" << Endl;
}
}
Options_.ServerBuilderMutator(builder);
builder.SetDefaultCompressionLevel(Options_.DefaultCompressionLevel);
Server_ = builder.BuildAndStart();
if (!Server_) {
ythrow yexception() << "can't start grpc server on " << server_address;
}
size_t index = 0;
for (IGRpcServicePtr service : Services_) {
// TODO: provide something else for services instead of ServerCompletionQueue
service->InitService(CQS_, Options_.Logger, index++);
}
Ts.reserve(Options_.WorkerThreads);
for (size_t i = 0; i < Options_.WorkerThreads; ++i) {
auto* cq = &CQS_[i % CQS_.size()];
Ts.push_back(SystemThreadFactory()->Run([cq] {
PullEvents(cq->get());
}));
}
if (Options_.ExternalListener) {
Options_.ExternalListener->Start();
}
}
void TGRpcServer::Stop() {
for (auto& service : Services_) {
service->StopService();
}
auto now = TInstant::Now();
if (Server_) {
i64 sec = Options_.GRpcShutdownDeadline.Seconds();
Y_ABORT_UNLESS(Options_.GRpcShutdownDeadline.NanoSecondsOfSecond() <= Max<i32>());
i32 nanosecOfSec = Options_.GRpcShutdownDeadline.NanoSecondsOfSecond();
Server_->Shutdown(gpr_timespec{sec, nanosecOfSec, GPR_TIMESPAN});
}
for (ui64 attempt = 0; ; ++attempt) {
bool unsafe = false;
size_t infly = 0;
for (auto& service : Services_) {
unsafe |= service->IsUnsafeToShutdown();
infly += service->RequestsInProgress();
}
if (!unsafe && !infly)
break;
auto spent = (TInstant::Now() - now).SecondsFloat();
if (attempt % 300 == 0) {
// don't log too much
Cerr << "GRpc shutdown warning: left infly: " << infly << ", spent: " << spent << " sec" << Endl;
}
if (!unsafe && spent > Options_.GRpcShutdownDeadline.SecondsFloat())
break;
Sleep(TDuration::MilliSeconds(10));
}
// Always shutdown the completion queue after the server.
for (auto& cq : CQS_) {
cq->Shutdown();
}
for (auto ti = Ts.begin(); ti != Ts.end(); ++ti) {
(*ti)->Join();
}
Ts.clear();
if (Options_.ExternalListener) {
Options_.ExternalListener->Stop();
}
}
ui16 TGRpcServer::GetPort() const {
return Options_.Port;
}
TString TGRpcServer::GetHost() const {
return Options_.Host;
}
const TVector<TGRpcServer::IGRpcServicePtr>& TGRpcServer::GetServices() const {
return Services_;
}
} // namespace NGrpc
|