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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
|
#pragma once
#include <library/cpp/unified_agent_client/client.h>
#include <library/cpp/unified_agent_client/client_proto_weighing.h>
#include <library/cpp/unified_agent_client/counters.h>
#include <library/cpp/unified_agent_client/logger.h>
#include <library/cpp/unified_agent_client/variant.h>
#include <library/cpp/unified_agent_client/proto/unified_agent.grpc.pb.h>
#include <library/cpp/unified_agent_client/grpc_io.h>
#include <library/cpp/logger/global/global.h>
#include <util/generic/deque.h>
#include <util/system/mutex.h>
namespace NUnifiedAgent::NPrivate {
class TClientSession;
class TGrpcCall;
class TForkProtector;
class TClient: public IClient {
public:
explicit TClient(const TClientParameters& parameters, std::shared_ptr<TForkProtector> forkProtector);
~TClient() override;
TClientSessionPtr CreateSession(const TSessionParameters& parameters) override;
void StartTracing(ELogPriority logPriority) override;
void FinishTracing() override;
inline const TIntrusivePtr<TClientCounters>& GetCounters() const noexcept {
return Counters;
}
inline NUnifiedAgentProto::UnifiedAgentService::Stub& GetStub() noexcept {
return *Stub;
}
TScopeLogger CreateSessionLogger();
inline const TClientParameters& GetParameters() const noexcept {
return Parameters;
}
inline grpc::CompletionQueue& GetCompletionQueue() noexcept {
return ActiveCompletionQueue->GetCompletionQueue();
}
void RegisterSession(TClientSession* session);
void UnregisterSession(TClientSession* session);
void PreFork();
void PostForkParent();
void PostForkChild();
void EnsureStarted();
private:
void EnsureStartedNoLock();
void EnsureStoppedNoLock();
private:
const TClientParameters Parameters;
std::shared_ptr<TForkProtector> ForkProtector;
TIntrusivePtr<TClientCounters> Counters;
TLog Log;
TLogger MainLogger;
TScopeLogger Logger;
std::shared_ptr<grpc::Channel> Channel;
std::unique_ptr<NUnifiedAgentProto::UnifiedAgentService::Stub> Stub;
THolder<TGrpcCompletionQueueHost> ActiveCompletionQueue;
std::atomic<size_t> SessionLogLabel;
TVector<TClientSession*> ActiveSessions;
bool Started;
bool Destroyed;
TAdaptiveLock Lock;
static std::atomic<ui64> Id;
};
class TForkProtector {
public:
TForkProtector();
void Register(TClient& client);
void Unregister(TClient& client);
static std::shared_ptr<TForkProtector> Get(bool createIfNotExists);
private:
static void PreFork();
static void PostForkParent();
static void PostForkChild();
private:
TVector<TClient*> Clients;
grpc::internal::GrpcLibrary GrpcInitializer;
bool Enabled;
TAdaptiveLock Lock;
static std::weak_ptr<TForkProtector> Instance;
static TMutex InstanceLock;
static bool SubscribedToForks;
};
class TClientSession: public IClientSession {
public:
TClientSession(const TIntrusivePtr<TClient>& client, const TSessionParameters& parameters);
~TClientSession();
void Send(TClientMessage&& message) override;
NThreading::TFuture<void> CloseAsync(TInstant deadline) override;
inline TClient& GetClient() noexcept {
return *Client;
}
inline TScopeLogger& GetLogger() noexcept {
return Logger;
}
inline TClientSessionCounters& GetCounters() noexcept {
return *Counters;
}
inline TAsyncJoiner& GetAsyncJoiner() noexcept {
return AsyncJoiner;
}
void PrepareInitializeRequest(NUnifiedAgentProto::Request& target);
void PrepareWriteBatchRequest(NUnifiedAgentProto::Request& target);
void Acknowledge(ui64 seqNo);
void OnGrpcCallInitialized(const TString& sessionId, ui64 lastSeqNo);
void OnGrpcCallFinished();
NThreading::TFuture<void> PreFork();
void PostForkParent();
void PostForkChild();
void SetAgentMaxReceiveMessage(size_t);
private:
enum class EPollingStatus {
Active,
Inactive
};
struct TCloseRequestedEvent {
TInstant Deadline;
};
struct TMessageReceivedEvent {
TClientMessage Message;
size_t Size;
};
struct TPurgeWriteQueueStats {
size_t PurgedMessages{};
size_t PurgedBytes{};
};
using TEvent = std::variant<TCloseRequestedEvent, TMessageReceivedEvent>;
public:
struct TPendingMessage {
TClientMessage Message;
size_t Size;
bool Skipped;
};
class TRequestBuilder {
public:
struct TAddResult;
public:
TRequestBuilder(NUnifiedAgentProto::Request &target, size_t RequestPayloadLimitBytes,
TFMaybe<size_t> serializedRequestLimitBytes);
TAddResult TryAddMessage(const TPendingMessage& message, size_t seqNo);
void ResetCounters();
inline size_t GetSerializedRequestSize() const {
return SerializedRequestSize;
}
inline size_t GetRequestPayloadSize() const {
return RequestPayloadSize;
}
public:
struct TAddResult {
bool LimitExceeded;
size_t NewRequestPayloadSize; // == actual value, if !LimitExceeded
size_t NewSerializedRequestSize; // == actual value, if !LimitExceeded
};
private:
struct TMetaItemBuilder {
size_t ItemIndex;
size_t ValueIndex{0};
};
private:
NUnifiedAgentProto::Request& Target;
TFMaybe<NPW::TRequest> PwTarget;
THashMap<TString, TMetaItemBuilder> MetaItems;
size_t RequestPayloadSize;
size_t RequestPayloadLimitBytes;
size_t SerializedRequestSize;
TFMaybe<size_t> SerializedRequestLimitBytes;
bool CountersInvalid;
};
private:
void MakeGrpcCall();
void DoClose();
void BeginClose(TInstant deadline);
void Poll();
TPurgeWriteQueueStats PurgeWriteQueue();
void DoStart();
private:
TAsyncJoiner AsyncJoiner;
TIntrusivePtr<TClient> Client;
TFMaybe<TString> OriginalSessionId;
TFMaybe<TString> SessionId;
TFMaybe<THashMap<TString, TString>> Meta;
TScopeLogger Logger;
bool CloseStarted;
bool ForcedCloseStarted;
bool Closed;
bool ForkInProgressLocal;
bool Started;
NThreading::TPromise<void> ClosePromise;
TIntrusivePtr<TGrpcCall> ActiveGrpcCall;
TDeque<TPendingMessage> WriteQueue;
size_t TrimmedCount;
size_t NextIndex;
TFMaybe<ui64> AckSeqNo;
TInstant PollerLastEventTimestamp;
TIntrusivePtr<TClientSessionCounters> Counters;
THolder<TGrpcTimer> MakeGrpcCallTimer;
THolder<TGrpcTimer> ForceCloseTimer;
THolder<TGrpcTimer> PollTimer;
ui64 GrpcInflightMessages;
ui64 GrpcInflightBytes;
std::atomic<size_t> InflightBytes;
bool CloseRequested;
size_t EventsBatchSize;
EPollingStatus PollingStatus;
THolder<TGrpcNotification> EventNotification;
bool EventNotificationTriggered;
TVector<TEvent> EventsBatch;
TVector<TEvent> SecondaryEventsBatch;
std::atomic<bool> ForkInProgress;
TAdaptiveLock Lock;
size_t MaxInflightBytes;
TFMaybe<size_t> AgentMaxReceiveMessage;
};
class TGrpcCall final: public TAtomicRefCount<TGrpcCall> {
public:
explicit TGrpcCall(TClientSession& session);
void Start();
~TGrpcCall();
void BeginClose(bool force);
void Poison();
void NotifyMessageAdded();
inline bool Initialized() const {
return Initialized_;
}
inline bool ReuseSessions() const {
return ReuseSessions_;
}
private:
void EndAccept(EIOStatus status);
void EndRead(EIOStatus status);
void EndWrite(EIOStatus status);
void EndFinish(EIOStatus status);
void EndWritesDone(EIOStatus);
void ScheduleWrite();
void BeginWritesDone();
bool CheckHasError(EIOStatus status, const char* method);
void SetError(const TString& error);
void EnsureFinishStarted();
void BeginRead();
void BeginWrite();
void ScheduleFinishOnError();
private:
TClientSession& Session;
TAsyncJoinerToken AsyncJoinerToken;
THolder<IIOCallback> AcceptTag;
THolder<IIOCallback> ReadTag;
THolder<IIOCallback> WriteTag;
THolder<IIOCallback> WritesDoneTag;
THolder<IIOCallback> FinishTag;
TScopeLogger Logger;
bool AcceptPending;
bool Initialized_;
bool ReadPending;
bool ReadsDone;
bool WritePending;
bool WritesBlocked;
bool WritesDonePending;
bool WritesDone;
bool ErrorOccured;
bool FinishRequested;
bool FinishStarted;
bool FinishDone;
bool Cancelled;
bool Poisoned;
bool PoisonPillSent;
bool ReuseSessions_;
grpc::Status FinishStatus;
grpc::ClientContext ClientContext;
std::unique_ptr<grpc::ClientAsyncReaderWriter<NUnifiedAgentProto::Request, NUnifiedAgentProto::Response>> ReaderWriter;
NUnifiedAgentProto::Request Request;
NUnifiedAgentProto::Response Response;
};
}
|