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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
|
// Copyright Epic Games, Inc. All Rights Reserved.
#include "hordeagent.h"
#include "hordetransportaes.h"
#include <zencore/basicfile.h>
#include <zencore/fmtutils.h>
#include <zencore/logging.h>
#include <zencore/trace.h>
ZEN_THIRD_PARTY_INCLUDES_START
#include <asio.hpp>
ZEN_THIRD_PARTY_INCLUDES_END
#include <cstring>
namespace zen::horde {
// --- AsyncHordeAgent ---
static const char*
GetStateName(AsyncHordeAgent::State S)
{
switch (S)
{
case AsyncHordeAgent::State::Idle:
return "idle";
case AsyncHordeAgent::State::Connecting:
return "connect";
case AsyncHordeAgent::State::WaitAgentAttach:
return "agent-attach";
case AsyncHordeAgent::State::SentFork:
return "fork";
case AsyncHordeAgent::State::WaitChildAttach:
return "child-attach";
case AsyncHordeAgent::State::Uploading:
return "upload";
case AsyncHordeAgent::State::Executing:
return "execute";
case AsyncHordeAgent::State::Polling:
return "poll";
case AsyncHordeAgent::State::Done:
return "done";
default:
return "unknown";
}
}
AsyncHordeAgent::AsyncHordeAgent(asio::io_context& IoContext) : m_IoContext(IoContext), m_Log(zen::logging::Get("horde.agent.async"))
{
}
AsyncHordeAgent::~AsyncHordeAgent()
{
Cancel();
}
void
AsyncHordeAgent::Start(AsyncAgentConfig Config, AsyncAgentCompletionHandler OnDone)
{
m_Config = std::move(Config);
m_OnDone = std::move(OnDone);
m_State = State::Connecting;
DoConnect();
}
void
AsyncHordeAgent::Cancel()
{
m_Cancelled = true;
if (m_Socket)
{
m_Socket->Close();
}
else if (m_Transport)
{
m_Transport->Close();
}
}
void
AsyncHordeAgent::DoConnect()
{
ZEN_TRACE_CPU("AsyncHordeAgent::DoConnect");
m_TcpTransport = std::make_unique<AsyncTcpComputeTransport>(m_IoContext);
auto Self = shared_from_this();
m_TcpTransport->AsyncConnect(m_Config.Machine, [this, Self](const std::error_code& Ec) { OnConnected(Ec); });
}
void
AsyncHordeAgent::OnConnected(const std::error_code& Ec)
{
if (Ec || m_Cancelled)
{
if (Ec)
{
ZEN_WARN("connect failed: {}", Ec.message());
}
Finish(false);
return;
}
// Optionally wrap with AES encryption
std::unique_ptr<AsyncComputeTransport> FinalTransport = std::move(m_TcpTransport);
if (m_Config.Machine.EncryptionMode == Encryption::AES)
{
FinalTransport = std::make_unique<AsyncAesComputeTransport>(m_Config.Machine.Key, std::move(FinalTransport), m_IoContext);
}
m_Transport = std::move(FinalTransport);
// Create the multiplexed socket and register channels
m_Socket = std::make_shared<AsyncComputeSocket>(std::move(m_Transport), m_IoContext);
m_AgentChannel = std::make_unique<AsyncAgentMessageChannel>(m_Socket, 0, m_IoContext);
m_ChildChannel = std::make_unique<AsyncAgentMessageChannel>(m_Socket, 100, m_IoContext);
m_Socket->RegisterChannel(
0,
[this](std::vector<uint8_t> Data) { m_AgentChannel->OnFrame(std::move(Data)); },
[this]() { m_AgentChannel->OnDetach(); });
m_Socket->RegisterChannel(
100,
[this](std::vector<uint8_t> Data) { m_ChildChannel->OnFrame(std::move(Data)); },
[this]() { m_ChildChannel->OnDetach(); });
m_Socket->StartRecvPump();
m_State = State::WaitAgentAttach;
DoWaitAgentAttach();
}
void
AsyncHordeAgent::DoWaitAgentAttach()
{
auto Self = shared_from_this();
m_AgentChannel->AsyncReadResponse(5000, [this, Self](AgentMessageType Type, const uint8_t* Data, size_t Size) {
OnAgentResponse(Type, Data, Size);
});
}
void
AsyncHordeAgent::OnAgentResponse(AgentMessageType Type, const uint8_t* /*Data*/, size_t /*Size*/)
{
if (m_Cancelled)
{
Finish(false);
return;
}
if (Type == AgentMessageType::None)
{
ZEN_WARN("timed out waiting for Attach on agent channel");
Finish(false);
return;
}
if (Type != AgentMessageType::Attach)
{
ZEN_WARN("expected Attach on agent channel, got 0x{:02x}", static_cast<int>(Type));
Finish(false);
return;
}
m_State = State::SentFork;
DoSendFork();
}
void
AsyncHordeAgent::DoSendFork()
{
m_AgentChannel->Fork(100, 4 * 1024 * 1024);
m_State = State::WaitChildAttach;
DoWaitChildAttach();
}
void
AsyncHordeAgent::DoWaitChildAttach()
{
auto Self = shared_from_this();
m_ChildChannel->AsyncReadResponse(5000, [this, Self](AgentMessageType Type, const uint8_t* Data, size_t Size) {
OnChildAttachResponse(Type, Data, Size);
});
}
void
AsyncHordeAgent::OnChildAttachResponse(AgentMessageType Type, const uint8_t* /*Data*/, size_t /*Size*/)
{
if (m_Cancelled)
{
Finish(false);
return;
}
if (Type == AgentMessageType::None)
{
ZEN_WARN("timed out waiting for Attach on child channel");
Finish(false);
return;
}
if (Type != AgentMessageType::Attach)
{
ZEN_WARN("expected Attach on child channel, got 0x{:02x}", static_cast<int>(Type));
Finish(false);
return;
}
m_State = State::Uploading;
m_CurrentBundleIndex = 0;
DoUploadNext();
}
void
AsyncHordeAgent::DoUploadNext()
{
if (m_Cancelled)
{
Finish(false);
return;
}
if (m_CurrentBundleIndex >= m_Config.Bundles.size())
{
// All bundles uploaded — proceed to execute
m_State = State::Executing;
DoExecute();
return;
}
const auto& [Locator, BundleDir] = m_Config.Bundles[m_CurrentBundleIndex];
m_ChildChannel->UploadFiles("", Locator.c_str());
// Enter the ReadBlob/Blob upload loop
auto Self = shared_from_this();
m_ChildChannel->AsyncReadResponse(1000, [this, Self](AgentMessageType Type, const uint8_t* Data, size_t Size) {
OnUploadResponse(Type, Data, Size);
});
}
void
AsyncHordeAgent::OnUploadResponse(AgentMessageType Type, const uint8_t* Data, size_t Size)
{
if (m_Cancelled)
{
Finish(false);
return;
}
if (Type == AgentMessageType::None)
{
if (m_ChildChannel->IsDetached())
{
ZEN_WARN("connection lost during upload");
Finish(false);
return;
}
// Timeout — retry read
auto Self = shared_from_this();
m_ChildChannel->AsyncReadResponse(1000, [this, Self](AgentMessageType Type, const uint8_t* Data, size_t Size) {
OnUploadResponse(Type, Data, Size);
});
return;
}
if (Type == AgentMessageType::WriteFilesResponse)
{
// This bundle upload is done — move to next
++m_CurrentBundleIndex;
DoUploadNext();
return;
}
if (Type == AgentMessageType::Exception)
{
ExceptionInfo Ex;
AsyncAgentMessageChannel::ReadException(Data, Size, Ex);
ZEN_ERROR("upload exception: {} - {}", Ex.Message, Ex.Description);
Finish(false);
return;
}
if (Type != AgentMessageType::ReadBlob)
{
ZEN_ERROR("unexpected message type 0x{:02x} during upload", static_cast<int>(Type));
Finish(false);
return;
}
// Handle ReadBlob request
BlobRequest Req;
AsyncAgentMessageChannel::ReadBlobRequest(Data, Size, Req);
const auto& [Locator, BundleDir] = m_Config.Bundles[m_CurrentBundleIndex];
const std::filesystem::path BlobPath = BundleDir / (std::string(Req.Locator) + ".blob");
std::error_code FsEc;
BasicFile File;
File.Open(BlobPath, BasicFile::Mode::kRead, FsEc);
if (FsEc)
{
ZEN_ERROR("cannot read blob file: '{}'", BlobPath);
Finish(false);
return;
}
const uint64_t TotalSize = File.FileSize();
const uint64_t Offset = static_cast<uint64_t>(Req.Offset);
if (Offset >= TotalSize)
{
ZEN_ERROR("blob request beyond end of file: offset={}, length={}, total_size={}", Offset, Req.Length, TotalSize);
m_ChildChannel->Blob(nullptr, 0);
}
else
{
const IoBuffer FileData = File.ReadRange(Offset, Min(Req.Length, TotalSize - Offset));
m_ChildChannel->Blob(static_cast<const uint8_t*>(FileData.GetData()), FileData.GetSize());
}
// Continue the upload loop
auto Self = shared_from_this();
m_ChildChannel->AsyncReadResponse(1000, [this, Self](AgentMessageType Type, const uint8_t* Data, size_t Size) {
OnUploadResponse(Type, Data, Size);
});
}
void
AsyncHordeAgent::DoExecute()
{
ZEN_TRACE_CPU("AsyncHordeAgent::DoExecute");
std::vector<const char*> ArgPtrs;
ArgPtrs.reserve(m_Config.Args.size());
for (const std::string& Arg : m_Config.Args)
{
ArgPtrs.push_back(Arg.c_str());
}
m_ChildChannel->Execute(m_Config.Executable.c_str(),
ArgPtrs.data(),
ArgPtrs.size(),
nullptr,
nullptr,
0,
m_Config.UseWine ? ExecuteProcessFlags::UseWine : ExecuteProcessFlags::None);
ZEN_INFO("remote execution started on [{}:{}] lease={}",
m_Config.Machine.GetConnectionAddress(),
m_Config.Machine.GetConnectionPort(),
m_Config.Machine.LeaseId);
m_State = State::Polling;
DoPoll();
}
void
AsyncHordeAgent::DoPoll()
{
if (m_Cancelled)
{
Finish(false);
return;
}
auto Self = shared_from_this();
m_ChildChannel->AsyncReadResponse(100, [this, Self](AgentMessageType Type, const uint8_t* Data, size_t Size) {
OnPollResponse(Type, Data, Size);
});
}
void
AsyncHordeAgent::OnPollResponse(AgentMessageType Type, const uint8_t* Data, size_t Size)
{
if (m_Cancelled)
{
Finish(false);
return;
}
switch (Type)
{
case AgentMessageType::None:
if (m_ChildChannel->IsDetached())
{
ZEN_WARN("connection lost during execution");
Finish(false);
}
else
{
// Timeout — poll again
DoPoll();
}
break;
case AgentMessageType::ExecuteOutput:
// Silently consume remote stdout (matching LogOutput=false in provisioner)
DoPoll();
break;
case AgentMessageType::ExecuteResult:
{
int32_t ExitCode = -1;
if (Size == sizeof(int32_t))
{
memcpy(&ExitCode, Data, sizeof(int32_t));
}
ZEN_INFO("remote process exited with code {} (lease={})", ExitCode, m_Config.Machine.LeaseId);
Finish(ExitCode == 0, ExitCode);
}
break;
case AgentMessageType::Exception:
{
ExceptionInfo Ex;
AsyncAgentMessageChannel::ReadException(Data, Size, Ex);
ZEN_ERROR("exception: {} - {}", Ex.Message, Ex.Description);
Finish(false);
}
break;
default:
DoPoll();
break;
}
}
void
AsyncHordeAgent::Finish(bool Success, int32_t ExitCode)
{
if (m_State == State::Done)
{
return; // Already finished
}
if (!Success)
{
ZEN_WARN("agent failed during {} (lease={})", GetStateName(m_State), m_Config.Machine.LeaseId);
}
m_State = State::Done;
if (m_Socket)
{
m_Socket->Close();
}
if (m_OnDone)
{
AsyncAgentResult Result;
Result.Success = Success;
Result.ExitCode = ExitCode;
Result.CoreCount = m_Config.Machine.LogicalCores;
auto Handler = std::move(m_OnDone);
m_OnDone = nullptr;
Handler(Result);
}
}
} // namespace zen::horde
|