aboutsummaryrefslogtreecommitdiff
path: root/src/zencompute/httporchestrator.cpp
blob: 6cbe01e0433410dc12230b8a477abe19376661b7 (plain) (blame)
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
// Copyright Epic Games, Inc. All Rights Reserved.

#include "zencompute/httporchestrator.h"

#if ZEN_WITH_COMPUTE_SERVICES

#	include <zencompute/orchestratorservice.h>
#	include <zencore/compactbinarybuilder.h>
#	include <zencore/logging.h>
#	include <zencore/string.h>
#	include <zencore/system.h>

namespace zen::compute {

// Worker IDs must be 3-64 characters and can only contain letters, numbers, underscores, and dashes
static bool
IsValidWorkerId(std::string_view Id)
{
	if (Id.size() < 3 || Id.size() > 64)
	{
		return false;
	}
	for (char c : Id)
	{
		if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || c == '-')
		{
			continue;
		}
		return false;
	}
	return true;
}

// Shared announce payload parser used by both the HTTP POST route and the
// WebSocket message handler.  Returns the worker ID on success (empty on
// validation failure).  The returned WorkerAnnouncement has string_view
// fields that reference the supplied CbObjectView, so the CbObject must
// outlive the returned announcement.
static std::string_view
ParseWorkerAnnouncement(const CbObjectView& Data, OrchestratorService::WorkerAnnouncement& Ann)
{
	Ann.Id	= Data["id"].AsString("");
	Ann.Uri = Data["uri"].AsString("");

	if (!IsValidWorkerId(Ann.Id))
	{
		return {};
	}

	if (!Ann.Uri.starts_with("http://") && !Ann.Uri.starts_with("https://"))
	{
		return {};
	}

	Ann.Hostname		 = Data["hostname"].AsString("");
	Ann.Platform		 = Data["platform"].AsString("");
	Ann.CpuUsagePercent	 = Data["cpu_usage"].AsFloat(0.0f);
	Ann.MemoryTotalBytes = Data["memory_total"].AsUInt64(0);
	Ann.MemoryUsedBytes	 = Data["memory_used"].AsUInt64(0);
	Ann.BytesReceived	 = Data["bytes_received"].AsUInt64(0);
	Ann.BytesSent		 = Data["bytes_sent"].AsUInt64(0);
	Ann.ActionsPending	 = Data["actions_pending"].AsInt32(0);
	Ann.ActionsRunning	 = Data["actions_running"].AsInt32(0);
	Ann.ActionsCompleted = Data["actions_completed"].AsInt32(0);
	Ann.ActiveQueues	 = Data["active_queues"].AsInt32(0);
	Ann.Provisioner		 = Data["provisioner"].AsString("");

	if (auto Metrics = Data["metrics"].AsObjectView())
	{
		Ann.Cpus = Metrics["lp_count"].AsInt32(0);
		if (Ann.Cpus <= 0)
		{
			Ann.Cpus = 1;
		}
	}

	return Ann.Id;
}

HttpOrchestratorService::HttpOrchestratorService(std::filesystem::path DataDir, bool EnableWorkerWebSocket)
: m_Service(std::make_unique<OrchestratorService>(std::move(DataDir), EnableWorkerWebSocket))
, m_Hostname(GetMachineName())
{
	m_Router.AddMatcher("workerid", [](std::string_view Segment) { return IsValidWorkerId(Segment); });
	m_Router.AddMatcher("clientid", [](std::string_view Segment) { return IsValidWorkerId(Segment); });

	// dummy endpoint for websocket clients
	m_Router.RegisterRoute(
		"ws",
		[this](HttpRouterRequest& Req) { Req.ServerRequest().WriteResponse(HttpResponseCode::OK); },
		HttpVerb::kGet);

	m_Router.RegisterRoute(
		"status",
		[this](HttpRouterRequest& Req) {
			CbObjectWriter Cbo;
			Cbo << "hostname" << std::string_view(m_Hostname);
			Req.ServerRequest().WriteResponse(HttpResponseCode::OK, Cbo.Save());
		},
		HttpVerb::kGet);

	m_Router.RegisterRoute(
		"provision",
		[this](HttpRouterRequest& Req) { Req.ServerRequest().WriteResponse(HttpResponseCode::OK, m_Service->GetWorkerList()); },
		HttpVerb::kPost);

	m_Router.RegisterRoute(
		"announce",
		[this](HttpRouterRequest& Req) {
			HttpServerRequest& HttpReq = Req.ServerRequest();

			CbObject Data = HttpReq.ReadPayloadObject();

			OrchestratorService::WorkerAnnouncement Ann;
			std::string_view						WorkerId = ParseWorkerAnnouncement(Data, Ann);

			if (WorkerId.empty())
			{
				return HttpReq.WriteResponse(HttpResponseCode::BadRequest,
											 HttpContentType::kText,
											 "Invalid worker announcement: id must be 3-64 alphanumeric/underscore/dash "
											 "characters and uri must start with http:// or https://");
			}

			m_Service->AnnounceWorker(Ann);

			HttpReq.WriteResponse(HttpResponseCode::OK);

#	if ZEN_WITH_WEBSOCKETS
			// Notify push thread that state may have changed
			m_PushEvent.Set();
#	endif
		},
		HttpVerb::kPost);

	m_Router.RegisterRoute(
		"agents",
		[this](HttpRouterRequest& Req) { Req.ServerRequest().WriteResponse(HttpResponseCode::OK, m_Service->GetWorkerList()); },
		HttpVerb::kGet);

	m_Router.RegisterRoute(
		"history",
		[this](HttpRouterRequest& Req) {
			HttpServerRequest& HttpReq = Req.ServerRequest();
			auto			   Params  = HttpReq.GetQueryParams();

			int	 Limit	  = 100;
			auto LimitStr = Params.GetValue("limit");
			if (!LimitStr.empty())
			{
				Limit = std::atoi(std::string(LimitStr).c_str());
			}

			HttpReq.WriteResponse(HttpResponseCode::OK, m_Service->GetProvisioningHistory(Limit));
		},
		HttpVerb::kGet);

	m_Router.RegisterRoute(
		"timeline/{workerid}",
		[this](HttpRouterRequest& Req) {
			HttpServerRequest& HttpReq = Req.ServerRequest();

			std::string_view WorkerId = Req.GetCapture(1);
			auto			 Params	  = HttpReq.GetQueryParams();

			auto FromStr  = Params.GetValue("from");
			auto ToStr	  = Params.GetValue("to");
			auto LimitStr = Params.GetValue("limit");

			std::optional<DateTime> From;
			std::optional<DateTime> To;

			if (!FromStr.empty())
			{
				auto Val = zen::ParseInt<uint64_t>(FromStr);
				if (!Val)
				{
					return HttpReq.WriteResponse(HttpResponseCode::BadRequest);
				}
				From = DateTime(*Val);
			}

			if (!ToStr.empty())
			{
				auto Val = zen::ParseInt<uint64_t>(ToStr);
				if (!Val)
				{
					return HttpReq.WriteResponse(HttpResponseCode::BadRequest);
				}
				To = DateTime(*Val);
			}

			int Limit = !LimitStr.empty() ? zen::ParseInt<int>(LimitStr).value_or(0) : 0;

			CbObject Result = m_Service->GetWorkerTimeline(WorkerId, From, To, Limit);

			if (!Result)
			{
				return HttpReq.WriteResponse(HttpResponseCode::NotFound);
			}

			HttpReq.WriteResponse(HttpResponseCode::OK, std::move(Result));
		},
		HttpVerb::kGet);

	m_Router.RegisterRoute(
		"timeline",
		[this](HttpRouterRequest& Req) {
			HttpServerRequest& HttpReq = Req.ServerRequest();
			auto			   Params  = HttpReq.GetQueryParams();

			auto FromStr = Params.GetValue("from");
			auto ToStr	 = Params.GetValue("to");

			DateTime From = DateTime(0);
			DateTime To	  = DateTime::Now();

			if (!FromStr.empty())
			{
				auto Val = zen::ParseInt<uint64_t>(FromStr);
				if (!Val)
				{
					return HttpReq.WriteResponse(HttpResponseCode::BadRequest);
				}
				From = DateTime(*Val);
			}

			if (!ToStr.empty())
			{
				auto Val = zen::ParseInt<uint64_t>(ToStr);
				if (!Val)
				{
					return HttpReq.WriteResponse(HttpResponseCode::BadRequest);
				}
				To = DateTime(*Val);
			}

			CbObject Result = m_Service->GetAllTimelines(From, To);

			HttpReq.WriteResponse(HttpResponseCode::OK, std::move(Result));
		},
		HttpVerb::kGet);

	// Client tracking endpoints

	m_Router.RegisterRoute(
		"clients",
		[this](HttpRouterRequest& Req) {
			HttpServerRequest& HttpReq = Req.ServerRequest();

			CbObject Data = HttpReq.ReadPayloadObject();

			OrchestratorService::ClientAnnouncement Ann;
			Ann.SessionId = Data["session_id"].AsObjectId(Oid::Zero);
			Ann.Hostname  = Data["hostname"].AsString("");
			Ann.Address	  = HttpReq.GetRemoteAddress();

			auto MetadataView = Data["metadata"].AsObjectView();
			if (MetadataView)
			{
				Ann.Metadata = CbObject::Clone(MetadataView);
			}

			std::string ClientId = m_Service->AnnounceClient(Ann);

			CbObjectWriter ResponseObj;
			ResponseObj << "id" << std::string_view(ClientId);
			HttpReq.WriteResponse(HttpResponseCode::OK, ResponseObj.Save());

#	if ZEN_WITH_WEBSOCKETS
			m_PushEvent.Set();
#	endif
		},
		HttpVerb::kPost);

	m_Router.RegisterRoute(
		"clients/{clientid}/update",
		[this](HttpRouterRequest& Req) {
			HttpServerRequest& HttpReq	= Req.ServerRequest();
			std::string_view   ClientId = Req.GetCapture(1);

			CbObject MetadataObj;
			CbObject Data = HttpReq.ReadPayloadObject();
			if (Data)
			{
				auto MetadataView = Data["metadata"].AsObjectView();
				if (MetadataView)
				{
					MetadataObj = CbObject::Clone(MetadataView);
				}
			}

			if (m_Service->UpdateClient(ClientId, std::move(MetadataObj)))
			{
				HttpReq.WriteResponse(HttpResponseCode::OK);
			}
			else
			{
				HttpReq.WriteResponse(HttpResponseCode::NotFound);
			}
		},
		HttpVerb::kPost);

	m_Router.RegisterRoute(
		"clients/{clientid}/complete",
		[this](HttpRouterRequest& Req) {
			HttpServerRequest& HttpReq	= Req.ServerRequest();
			std::string_view   ClientId = Req.GetCapture(1);

			if (m_Service->CompleteClient(ClientId))
			{
				HttpReq.WriteResponse(HttpResponseCode::OK);
			}
			else
			{
				HttpReq.WriteResponse(HttpResponseCode::NotFound);
			}

#	if ZEN_WITH_WEBSOCKETS
			m_PushEvent.Set();
#	endif
		},
		HttpVerb::kPost);

	m_Router.RegisterRoute(
		"clients",
		[this](HttpRouterRequest& Req) { Req.ServerRequest().WriteResponse(HttpResponseCode::OK, m_Service->GetClientList()); },
		HttpVerb::kGet);

	m_Router.RegisterRoute(
		"clients/history",
		[this](HttpRouterRequest& Req) {
			HttpServerRequest& HttpReq = Req.ServerRequest();
			auto			   Params  = HttpReq.GetQueryParams();

			int	 Limit	  = 100;
			auto LimitStr = Params.GetValue("limit");
			if (!LimitStr.empty())
			{
				Limit = std::atoi(std::string(LimitStr).c_str());
			}

			HttpReq.WriteResponse(HttpResponseCode::OK, m_Service->GetClientHistory(Limit));
		},
		HttpVerb::kGet);

#	if ZEN_WITH_WEBSOCKETS

	// Start the WebSocket push thread
	m_PushEnabled.store(true);
	m_PushThread = std::thread([this] { PushThreadFunction(); });
#	endif
}

HttpOrchestratorService::~HttpOrchestratorService()
{
	Shutdown();
}

void
HttpOrchestratorService::Shutdown()
{
#	if ZEN_WITH_WEBSOCKETS
	if (!m_PushEnabled.exchange(false))
	{
		return;
	}

	// Stop the push thread first, before touching connections.  This ensures
	// the push thread is no longer reading m_WsConnections or calling into
	// m_Service when we start tearing things down.
	m_PushEvent.Set();
	if (m_PushThread.joinable())
	{
		m_PushThread.join();
	}

	// Clean up worker WebSocket connections — collect IDs under lock, then
	// notify the service outside the lock to avoid lock-order inversions.
	std::vector<std::string> WorkerIds;
	m_WorkerWsLock.WithExclusiveLock([&] {
		WorkerIds.reserve(m_WorkerWsMap.size());
		for (const auto& [Conn, Id] : m_WorkerWsMap)
		{
			WorkerIds.push_back(Id);
		}
		m_WorkerWsMap.clear();
	});
	for (const auto& Id : WorkerIds)
	{
		m_Service->SetWorkerWebSocketConnected(Id, false);
	}

	// Now that the push thread is gone, release all dashboard connections.
	m_WsConnectionsLock.WithExclusiveLock([&] { m_WsConnections.clear(); });
#	endif
}

const char*
HttpOrchestratorService::BaseUri() const
{
	return "/orch/";
}

void
HttpOrchestratorService::HandleRequest(HttpServerRequest& Request)
{
	if (m_Router.HandleRequest(Request) == false)
	{
		ZEN_WARN("No route found for {0}", Request.RelativeUri());
	}
}

//////////////////////////////////////////////////////////////////////////
//
// IWebSocketHandler
//

#	if ZEN_WITH_WEBSOCKETS
void
HttpOrchestratorService::OnWebSocketOpen(Ref<WebSocketConnection> Connection)
{
	if (!m_PushEnabled.load())
	{
		return;
	}

	ZEN_INFO("WebSocket client connected");

	m_WsConnectionsLock.WithExclusiveLock([&] { m_WsConnections.push_back(std::move(Connection)); });

	// Wake push thread to send initial state immediately
	m_PushEvent.Set();
}

void
HttpOrchestratorService::OnWebSocketMessage(WebSocketConnection& Conn, const WebSocketMessage& Msg)
{
	// Only handle binary messages from workers when the feature is enabled.
	if (!m_Service->IsWorkerWebSocketEnabled() || Msg.Opcode != WebSocketOpcode::kBinary)
	{
		return;
	}

	std::string WorkerId = HandleWorkerWebSocketMessage(Msg);
	if (WorkerId.empty())
	{
		return;
	}

	// Check if this is a new worker WebSocket connection
	bool IsNewWorkerWs = false;
	m_WorkerWsLock.WithExclusiveLock([&] {
		auto It = m_WorkerWsMap.find(&Conn);
		if (It == m_WorkerWsMap.end())
		{
			m_WorkerWsMap[&Conn] = WorkerId;
			IsNewWorkerWs		 = true;
		}
	});

	if (IsNewWorkerWs)
	{
		m_Service->SetWorkerWebSocketConnected(WorkerId, true);
	}

	m_PushEvent.Set();
}

std::string
HttpOrchestratorService::HandleWorkerWebSocketMessage(const WebSocketMessage& Msg)
{
	// Workers send CbObject in native binary format over the WebSocket to
	// avoid the lossy CbObject↔JSON round-trip.
	CbObject Data = CbObject::MakeView(Msg.Payload.GetData());
	if (!Data)
	{
		ZEN_WARN("worker WebSocket message is not a valid CbObject");
		return {};
	}

	OrchestratorService::WorkerAnnouncement Ann;
	std::string_view						WorkerId = ParseWorkerAnnouncement(Data, Ann);
	if (WorkerId.empty())
	{
		ZEN_WARN("invalid worker announcement via WebSocket");
		return {};
	}

	m_Service->AnnounceWorker(Ann);
	return std::string(WorkerId);
}

void
HttpOrchestratorService::OnWebSocketClose(WebSocketConnection&				Conn,
										  [[maybe_unused]] uint16_t			Code,
										  [[maybe_unused]] std::string_view Reason)
{
	ZEN_INFO("WebSocket client disconnected (code {})", Code);

	// Check if this was a worker WebSocket connection; collect the ID under
	// the worker lock, then notify the service outside the lock.
	std::string DisconnectedWorkerId;
	m_WorkerWsLock.WithExclusiveLock([&] {
		auto It = m_WorkerWsMap.find(&Conn);
		if (It != m_WorkerWsMap.end())
		{
			DisconnectedWorkerId = std::move(It->second);
			m_WorkerWsMap.erase(It);
		}
	});

	if (!DisconnectedWorkerId.empty())
	{
		m_Service->SetWorkerWebSocketConnected(DisconnectedWorkerId, false);
		m_PushEvent.Set();
	}

	if (!m_PushEnabled.load())
	{
		return;
	}

	// Remove from dashboard connections
	m_WsConnectionsLock.WithExclusiveLock([&] {
		auto It = std::remove_if(m_WsConnections.begin(), m_WsConnections.end(), [&Conn](const Ref<WebSocketConnection>& C) {
			return C.Get() == &Conn;
		});
		m_WsConnections.erase(It, m_WsConnections.end());
	});
}
#	endif

//////////////////////////////////////////////////////////////////////////
//
// Push thread
//

#	if ZEN_WITH_WEBSOCKETS
void
HttpOrchestratorService::PushThreadFunction()
{
	SetCurrentThreadName("orch_ws_push");

	while (m_PushEnabled.load())
	{
		m_PushEvent.Wait(2000);
		m_PushEvent.Reset();

		if (!m_PushEnabled.load())
		{
			break;
		}

		// Snapshot current connections
		std::vector<Ref<WebSocketConnection>> Connections;
		m_WsConnectionsLock.WithSharedLock([&] { Connections = m_WsConnections; });

		if (Connections.empty())
		{
			continue;
		}

		// Build combined JSON with worker list, provisioning history, clients, and client history
		CbObject WorkerList	   = m_Service->GetWorkerList();
		CbObject History	   = m_Service->GetProvisioningHistory(50);
		CbObject ClientList	   = m_Service->GetClientList();
		CbObject ClientHistory = m_Service->GetClientHistory(50);

		ExtendableStringBuilder<4096> JsonBuilder;
		JsonBuilder.Append("{");
		JsonBuilder.Append(fmt::format("\"hostname\":\"{}\",", m_Hostname));

		// Emit workers array from worker list
		ExtendableStringBuilder<2048> WorkerJson;
		WorkerList.ToJson(WorkerJson);
		std::string_view WorkerJsonView = WorkerJson.ToView();
		// Strip outer braces: {"workers":[...]} -> "workers":[...]
		if (WorkerJsonView.size() >= 2)
		{
			JsonBuilder.Append(WorkerJsonView.substr(1, WorkerJsonView.size() - 2));
		}

		JsonBuilder.Append(",");

		// Emit events array from history
		ExtendableStringBuilder<2048> HistoryJson;
		History.ToJson(HistoryJson);
		std::string_view HistoryJsonView = HistoryJson.ToView();
		if (HistoryJsonView.size() >= 2)
		{
			JsonBuilder.Append(HistoryJsonView.substr(1, HistoryJsonView.size() - 2));
		}

		JsonBuilder.Append(",");

		// Emit clients array from client list
		ExtendableStringBuilder<2048> ClientJson;
		ClientList.ToJson(ClientJson);
		std::string_view ClientJsonView = ClientJson.ToView();
		if (ClientJsonView.size() >= 2)
		{
			JsonBuilder.Append(ClientJsonView.substr(1, ClientJsonView.size() - 2));
		}

		JsonBuilder.Append(",");

		// Emit client_events array from client history
		ExtendableStringBuilder<2048> ClientHistoryJson;
		ClientHistory.ToJson(ClientHistoryJson);
		std::string_view ClientHistoryJsonView = ClientHistoryJson.ToView();
		if (ClientHistoryJsonView.size() >= 2)
		{
			JsonBuilder.Append(ClientHistoryJsonView.substr(1, ClientHistoryJsonView.size() - 2));
		}

		JsonBuilder.Append("}");
		std::string_view Json = JsonBuilder.ToView();

		// Broadcast to all connected clients, prune closed ones
		bool HadClosedConnections = false;

		for (auto& Conn : Connections)
		{
			if (Conn->IsOpen())
			{
				Conn->SendText(Json);
			}
			else
			{
				HadClosedConnections = true;
			}
		}

		if (HadClosedConnections)
		{
			m_WsConnectionsLock.WithExclusiveLock([&] {
				auto It = std::remove_if(m_WsConnections.begin(), m_WsConnections.end(), [](const Ref<WebSocketConnection>& C) {
					return !C->IsOpen();
				});
				m_WsConnections.erase(It, m_WsConnections.end());
			});
		}
	}
}
#	endif

}  // namespace zen::compute

#endif