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
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
|
// Copyright Epic Games, Inc. All Rights Reserved.
#include "hubservice.h"
#include "hydration.h"
#include <zencore/compactbinarybuilder.h>
#include <zencore/filesystem.h>
#include <zencore/fmtutils.h>
#include <zencore/logging.h>
#include <zencore/scopeguard.h>
#include <zencore/system.h>
#include <zenutil/zenserverprocess.h>
ZEN_THIRD_PARTY_INCLUDES_START
#include <EASTL/fixed_vector.h>
#include <asio.hpp>
ZEN_THIRD_PARTY_INCLUDES_END
#include <unordered_map>
#include <unordered_set>
namespace zen {
///////////////////////////////////////////////////////////////////////////
/**
* A timeline of events with sequence IDs and timestamps. Used to
* track significant events for broadcasting to listeners.
*/
class EventTimeline
{
public:
EventTimeline() { m_Events.reserve(1024); }
~EventTimeline() {}
EventTimeline(const EventTimeline&) = delete;
EventTimeline& operator=(const EventTimeline&) = delete;
void RecordEvent(std::string_view EventTag, CbObject EventMetadata)
{
const uint64_t SequenceId = m_NextEventId++;
const auto Now = std::chrono::steady_clock::now();
RwLock::ExclusiveLockScope _(m_Lock);
m_Events.emplace_back(SequenceId, EventTag, Now, std::move(EventMetadata));
}
struct EventRecord
{
uint64_t SequenceId;
std::string Tag;
std::chrono::steady_clock::time_point Timestamp;
CbObject EventMetadata;
EventRecord(uint64_t InSequenceId,
std::string_view InTag,
std::chrono::steady_clock::time_point InTimestamp,
CbObject InEventMetadata = CbObject())
: SequenceId(InSequenceId)
, Tag(InTag)
, Timestamp(InTimestamp)
, EventMetadata(InEventMetadata)
{
}
};
/**
* Iterate over events that have a SequenceId greater than SinceEventId
*
* @param Callback A callable that takes a const EventRecord&
* @param SinceEventId The SequenceId to compare against
*/
void IterateEventsSince(auto&& Callback, uint64_t SinceEventId)
{
// Hold the lock for as short a time as possible
eastl::fixed_vector<EventRecord, 128> EventsToProcess;
m_Lock.WithSharedLock([&] {
for (auto& Event : m_Events)
{
if (Event.SequenceId > SinceEventId)
{
EventsToProcess.push_back(Event);
}
}
});
// Now invoke the callback outside the lock
for (auto& Event : EventsToProcess)
{
Callback(Event);
}
}
/**
* Trim events up to (and including) the given SequenceId. Intended
* to be used for cleaning up events which are not longer interesting.
*
* @param UpToEventId The SequenceId up to which events should be removed
*/
void TrimEventsUpTo(uint64_t UpToEventId)
{
RwLock::ExclusiveLockScope _(m_Lock);
auto It = std::remove_if(m_Events.begin(), m_Events.end(), [UpToEventId](const EventRecord& Event) {
return Event.SequenceId <= UpToEventId;
});
m_Events.erase(It, m_Events.end());
}
private:
std::atomic<uint64_t> m_NextEventId{0};
RwLock m_Lock;
std::vector<EventRecord> m_Events;
};
//////////////////////////////////////////////////////////////////////////
struct ResourceMetrics
{
uint64_t DiskUsageBytes = 0;
uint64_t MemoryUsageBytes = 0;
};
/**
* Storage Server Instance
*
* This class manages the lifecycle of a storage server instance, and
* provides functions to query its state. There should be one instance
* per module ID.
*/
struct StorageServerInstance
{
StorageServerInstance(ZenServerEnvironment& RunEnvironment,
std::string_view ModuleId,
std::filesystem::path FileHydrationPath,
std::filesystem::path HydrationTempPath);
~StorageServerInstance();
void Provision();
void Deprovision();
void Hibernate();
void Wake();
const ResourceMetrics& GetResourceMetrics() const { return m_ResourceMetrics; }
inline std::string_view GetModuleId() const { return m_ModuleId; }
inline bool IsProvisioned() const { return m_IsProvisioned.load(); }
inline uint16_t GetBasePort() const { return m_ServerInstance.GetBasePort(); }
private:
void WakeLocked();
RwLock m_Lock;
std::string m_ModuleId;
std::atomic<bool> m_IsProvisioned{false};
std::atomic<bool> m_IsHibernated{false};
ZenServerInstance m_ServerInstance;
std::filesystem::path m_BaseDir;
std::filesystem::path m_TempDir;
std::filesystem::path m_HydrationPath;
ResourceMetrics m_ResourceMetrics;
void SpawnServerProcess();
void Hydrate();
void Dehydrate();
};
StorageServerInstance::StorageServerInstance(ZenServerEnvironment& RunEnvironment,
std::string_view ModuleId,
std::filesystem::path FileHydrationPath,
std::filesystem::path HydrationTempPath)
: m_ModuleId(ModuleId)
, m_ServerInstance(RunEnvironment, ZenServerInstance::ServerMode::kStorageServer)
, m_HydrationPath(FileHydrationPath)
{
m_BaseDir = RunEnvironment.CreateChildDir(ModuleId);
m_TempDir = HydrationTempPath / ModuleId;
}
StorageServerInstance::~StorageServerInstance()
{
}
void
StorageServerInstance::SpawnServerProcess()
{
ZEN_ASSERT(!m_ServerInstance.IsRunning(), "Storage server instance for module '{}' is already running", m_ModuleId);
m_ServerInstance.SetServerExecutablePath(GetRunningExecutablePath());
m_ServerInstance.SetDataDir(m_BaseDir);
const uint16_t BasePort = m_ServerInstance.SpawnServerAndWaitUntilReady();
ZEN_DEBUG("Storage server instance for module '{}' started, listening on port {}", m_ModuleId, BasePort);
m_ServerInstance.EnableShutdownOnDestroy();
}
void
StorageServerInstance::Provision()
{
RwLock::ExclusiveLockScope _(m_Lock);
if (m_IsProvisioned)
{
ZEN_WARN("Storage server instance for module '{}' is already provisioned", m_ModuleId);
return;
}
if (m_IsHibernated)
{
WakeLocked();
}
else
{
ZEN_INFO("Provisioning storage server instance for module '{}', at '{}'", m_ModuleId, m_BaseDir);
Hydrate();
SpawnServerProcess();
}
m_IsProvisioned = true;
}
void
StorageServerInstance::Deprovision()
{
RwLock::ExclusiveLockScope _(m_Lock);
if (!m_IsProvisioned)
{
ZEN_WARN("Attempted to deprovision storage server instance for module '{}' which is not provisioned", m_ModuleId);
return;
}
ZEN_INFO("Deprovisioning storage server instance for module '{}'", m_ModuleId);
m_ServerInstance.Shutdown();
Dehydrate();
m_IsProvisioned = false;
}
void
StorageServerInstance::Hibernate()
{
// Signal server to shut down, but keep data around for later wake
RwLock::ExclusiveLockScope _(m_Lock);
if (!m_IsProvisioned)
{
ZEN_WARN("Attempted to hibernate storage server instance for module '{}' which is not provisioned", m_ModuleId);
return;
}
if (m_IsHibernated)
{
ZEN_WARN("Storage server instance for module '{}' is already hibernated", m_ModuleId);
return;
}
if (!m_ServerInstance.IsRunning())
{
ZEN_WARN("Attempted to hibernate storage server instance for module '{}' which is not running", m_ModuleId);
// This is an unexpected state. Should consider the instance invalid?
return;
}
try
{
m_ServerInstance.Shutdown();
m_IsHibernated = true;
m_IsProvisioned = false;
return;
}
catch (const std::exception& Ex)
{
ZEN_ERROR("Failed to hibernate storage server instance for module '{}': {}", m_ModuleId, Ex.what());
}
}
void
StorageServerInstance::Wake()
{
RwLock::ExclusiveLockScope _(m_Lock);
WakeLocked();
}
void
StorageServerInstance::WakeLocked()
{
// Start server in-place using existing data
if (!m_IsHibernated)
{
ZEN_WARN("Attempted to wake storage server instance for module '{}' which is not hibernated", m_ModuleId);
return;
}
ZEN_ASSERT(!m_ServerInstance.IsRunning(), "Storage server instance for module '{}' is already running", m_ModuleId);
try
{
SpawnServerProcess();
m_IsHibernated = false;
}
catch (const std::exception& Ex)
{
ZEN_ERROR("Failed to wake storage server instance for module '{}': {}", m_ModuleId, Ex.what());
// TODO: this instance should be marked as invalid
}
}
void
StorageServerInstance::Hydrate()
{
HydrationConfig Config{.ServerStateDir = m_BaseDir,
.TempDir = m_TempDir,
.ModuleId = m_ModuleId,
.TargetSpecification = WideToUtf8(m_HydrationPath.native())};
std::unique_ptr<HydrationStrategyBase> Hydrator = CreateFileHydrator();
Hydrator->Configure(Config);
Hydrator->Hydrate();
}
void
StorageServerInstance::Dehydrate()
{
HydrationConfig Config{.ServerStateDir = m_BaseDir,
.TempDir = m_TempDir,
.ModuleId = m_ModuleId,
.TargetSpecification = WideToUtf8(m_HydrationPath.native())};
std::unique_ptr<HydrationStrategyBase> Hydrator = CreateFileHydrator();
Hydrator->Configure(Config);
Hydrator->Dehydrate();
}
//////////////////////////////////////////////////////////////////////////
struct HttpHubService::Impl
{
Impl(const Impl&) = delete;
Impl& operator=(const Impl&) = delete;
Impl();
~Impl();
void Initialize(std::filesystem::path HubBaseDir, std::filesystem::path ChildBaseDir)
{
m_RunEnvironment.InitializeForHub(HubBaseDir, ChildBaseDir);
m_FileHydrationPath = m_RunEnvironment.CreateChildDir("hydration_storage");
ZEN_INFO("using file hydration path: '{}'", m_FileHydrationPath);
m_HydrationTempPath = m_RunEnvironment.CreateChildDir("hydration_temp");
ZEN_INFO("using hydration temp path: '{}'", m_HydrationTempPath);
// This is necessary to ensure the hub assigns a distinct port range.
// We need to do this primarily because otherwise automated tests will
// fail as the test runner will create processes in the default range.
// We should probably make this configurable or dynamic for maximum
// flexibility, and to allow running multiple hubs on the same host if
// necessary.
m_RunEnvironment.SetNextPortNumber(21000);
}
void Cleanup()
{
RwLock::ExclusiveLockScope _(m_Lock);
m_Instances.clear();
}
struct ProvisionedInstanceInfo
{
std::string BaseUri;
uint16_t Port;
};
/**
* Provision a storage server instance for the given module ID.
*
* @param ModuleId The ID of the module to provision.
* @param OutInfo If successful, information about the provisioned instance will be returned here.
* @param OutReason If unsuccessful, the reason will be returned here.
*/
bool Provision(std::string_view ModuleId, ProvisionedInstanceInfo& OutInfo, std::string& OutReason)
{
StorageServerInstance* Instance = nullptr;
bool IsNewInstance = false;
{
RwLock::ExclusiveLockScope _(m_Lock);
if (auto It = m_Instances.find(std::string(ModuleId)); It == m_Instances.end())
{
std::string Reason;
if (!CanProvisionInstance(ModuleId, /* out */ Reason))
{
ZEN_WARN("Cannot provision new storage server instance for module '{}': {}", ModuleId, Reason);
OutReason = Reason;
return false;
}
IsNewInstance = true;
auto NewInstance =
std::make_unique<StorageServerInstance>(m_RunEnvironment, ModuleId, m_FileHydrationPath, m_HydrationTempPath);
Instance = NewInstance.get();
m_Instances.emplace(std::string(ModuleId), std::move(NewInstance));
ZEN_INFO("Created new storage server instance for module '{}'", ModuleId);
}
else
{
Instance = It->second.get();
}
m_ProvisioningModules.emplace(std::string(ModuleId));
}
ZEN_ASSERT(Instance != nullptr);
auto RemoveProvisioningModule = MakeGuard([&] {
RwLock::ExclusiveLockScope _(m_Lock);
m_ProvisioningModules.erase(std::string(ModuleId));
});
// NOTE: this is done while not holding the lock, as provisioning may take time
// and we don't want to block other operations. We track which modules are being
// provisioned using m_ProvisioningModules, and reject attempts to provision/deprovision
// those modules while in this state.
UpdateStats();
try
{
Instance->Provision();
}
catch (const std::exception& Ex)
{
ZEN_ERROR("Failed to provision storage server instance for module '{}': {}", ModuleId, Ex.what());
if (IsNewInstance)
{
// Clean up
RwLock::ExclusiveLockScope _(m_Lock);
m_Instances.erase(std::string(ModuleId));
}
return false;
}
OutInfo.Port = Instance->GetBasePort();
// TODO: base URI? Would need to know what host name / IP to use
return true;
}
/**
* Deprovision a storage server instance for the given module ID.
*
* @param ModuleId The ID of the module to deprovision.
* @param OutReason If unsuccessful, the reason will be returned here.
* @return true if the instance was found and deprovisioned, false otherwise.
*/
bool Deprovision(const std::string& ModuleId, std::string& OutReason)
{
std::unique_ptr<StorageServerInstance> Instance;
{
RwLock::ExclusiveLockScope _(m_Lock);
if (auto It = m_ProvisioningModules.find(ModuleId); It != m_ProvisioningModules.end())
{
OutReason = fmt::format("Module '{}' is currently being provisioned", ModuleId);
ZEN_WARN("Attempted to deprovision module '{}' which is currently being provisioned", ModuleId);
return false;
}
if (auto It = m_Instances.find(ModuleId); It == m_Instances.end())
{
ZEN_WARN("Attempted to deprovision non-existent module '{}'", ModuleId);
// Not found, OutReason should be empty
return false;
}
else
{
Instance = std::move(It->second);
m_Instances.erase(It);
m_DeprovisioningModules.emplace(ModuleId);
}
}
// The module is deprovisioned outside the lock to avoid blocking other operations.
//
// To ensure that no new provisioning can occur while we're deprovisioning,
// we add the module ID to m_DeprovisioningModules and remove it once
// deprovisioning is complete.
auto _ = MakeGuard([&] {
RwLock::ExclusiveLockScope _(m_Lock);
m_DeprovisioningModules.erase(ModuleId);
});
Instance->Deprovision();
return true;
}
/**
* Find a storage server instance for the given module ID.
*
* Beware that as this returns a raw pointer to the instance, the caller must ensure
* that the instance is not deprovisioned while in use.
*
* @param ModuleId The ID of the module to find.
* @param OutInstance If found, the instance will be returned here.
* @return true if the instance was found, false otherwise.
*/
bool Find(std::string_view ModuleId, StorageServerInstance** OutInstance = nullptr)
{
RwLock::SharedLockScope _(m_Lock);
if (auto It = m_Instances.find(std::string(ModuleId)); It != m_Instances.end())
{
if (OutInstance)
{
*OutInstance = It->second.get();
}
return true;
}
else if (OutInstance)
{
*OutInstance = nullptr;
}
return false;
}
/**
* Enumerate all storage server instances.
*
* @param Callback The callback to invoke for each instance. Note that you should
* not do anything heavyweight in the callback as it is invoked while holding
* a shared lock.
*/
void EnumerateModules(auto&& Callback)
{
RwLock::SharedLockScope _(m_Lock);
for (auto& It : m_Instances)
{
Callback(*It.second);
}
}
int GetInstanceCount()
{
RwLock::SharedLockScope _(m_Lock);
return gsl::narrow_cast<int>(m_Instances.size());
}
inline int GetInstanceLimit() { return m_InstanceLimit; }
inline int GetMaxInstanceCount() { return m_MaxInstanceCount; }
private:
ZenServerEnvironment m_RunEnvironment;
std::filesystem::path m_FileHydrationPath;
std::filesystem::path m_HydrationTempPath;
RwLock m_Lock;
std::unordered_map<std::string, std::unique_ptr<StorageServerInstance>> m_Instances;
std::unordered_set<std::string> m_DeprovisioningModules;
std::unordered_set<std::string> m_ProvisioningModules;
int m_MaxInstanceCount = 0;
void UpdateStats();
// Capacity tracking
int m_InstanceLimit = 1000;
ResourceMetrics m_ResourceLimits;
SystemMetrics m_HostMetrics;
void UpdateCapacityMetrics();
bool CanProvisionInstance(std::string_view ModuleId, std::string& OutReason);
};
HttpHubService::Impl::Impl()
{
m_HostMetrics = zen::GetSystemMetrics();
m_ResourceLimits.DiskUsageBytes = 1000ull * 1024 * 1024 * 1024;
m_ResourceLimits.MemoryUsageBytes = 16ull * 1024 * 1024 * 1024;
}
HttpHubService::Impl::~Impl()
{
try
{
ZEN_INFO("Hub service shutting down, deprovisioning any current instances");
m_Lock.WithExclusiveLock([this] {
for (auto& [ModuleId, Instance] : m_Instances)
{
Instance->Deprovision();
}
m_Instances.clear();
});
}
catch (const std::exception& e)
{
ZEN_WARN("Exception during hub service shutdown: {}", e.what());
}
}
void
HttpHubService::Impl::UpdateCapacityMetrics()
{
m_HostMetrics = zen::GetSystemMetrics();
// Update per-instance metrics
}
void
HttpHubService::Impl::UpdateStats()
{
m_Lock.WithSharedLock([this] { m_MaxInstanceCount = Max(m_MaxInstanceCount, gsl::narrow_cast<int>(m_Instances.size())); });
}
bool
HttpHubService::Impl::CanProvisionInstance(std::string_view ModuleId, std::string& OutReason)
{
if (m_DeprovisioningModules.find(std::string(ModuleId)) != m_DeprovisioningModules.end())
{
OutReason = fmt::format("module '{}' is currently being deprovisioned", ModuleId);
return false;
}
if (m_ProvisioningModules.find(std::string(ModuleId)) != m_ProvisioningModules.end())
{
OutReason = fmt::format("module '{}' is currently being provisioned", ModuleId);
return false;
}
if (gsl::narrow_cast<int>(m_Instances.size()) >= m_InstanceLimit)
{
OutReason = fmt::format("instance limit exceeded ({})", m_InstanceLimit);
return false;
}
// TODO: handle additional resource metrics
return true;
}
///////////////////////////////////////////////////////////////////////////
HttpHubService::HttpHubService(std::filesystem::path HubBaseDir, std::filesystem::path ChildBaseDir) : m_Impl(std::make_unique<Impl>())
{
using namespace std::literals;
m_Impl->Initialize(HubBaseDir, ChildBaseDir);
m_Router.AddMatcher("moduleid", [](std::string_view Str) -> bool {
for (const auto C : Str)
{
if (std::isalnum(C) || C == '-')
{
// fine
}
else
{
// not fine
return false;
}
}
return true;
});
m_Router.RegisterRoute(
"status",
[this](HttpRouterRequest& Req) {
CbObjectWriter Obj;
Obj.BeginArray("modules");
m_Impl->EnumerateModules([&Obj](StorageServerInstance& Instance) {
Obj.BeginObject();
Obj << "moduleId" << Instance.GetModuleId();
Obj << "provisioned" << Instance.IsProvisioned();
Obj.EndObject();
});
Obj.EndArray();
Req.ServerRequest().WriteResponse(HttpResponseCode::OK, Obj.Save());
},
HttpVerb::kGet);
m_Router.RegisterRoute(
"modules/{moduleid}",
[this](HttpRouterRequest& Req) {
std::string_view ModuleId = Req.GetCapture(1);
if (Req.ServerRequest().RequestVerb() == HttpVerb::kDelete)
{
HandleModuleDelete(Req.ServerRequest(), ModuleId);
}
else
{
HandleModuleGet(Req.ServerRequest(), ModuleId);
}
},
HttpVerb::kGet | HttpVerb::kDelete);
m_Router.RegisterRoute(
"modules/{moduleid}/provision",
[this](HttpRouterRequest& Req) {
std::string_view ModuleId = Req.GetCapture(1);
std::string FailureReason = "unknown";
HttpResponseCode ResponseCode = HttpResponseCode::OK;
try
{
Impl::ProvisionedInstanceInfo Info;
if (m_Impl->Provision(ModuleId, /* out */ Info, /* out */ FailureReason))
{
CbObjectWriter Obj;
Obj << "moduleId" << ModuleId;
Obj << "baseUri" << Info.BaseUri;
Obj << "port" << Info.Port;
Req.ServerRequest().WriteResponse(HttpResponseCode::OK, Obj.Save());
return;
}
else
{
ResponseCode = HttpResponseCode::BadRequest;
}
}
catch (const std::exception& Ex)
{
ZEN_ERROR("Exception while provisioning module '{}': {}", ModuleId, Ex.what());
FailureReason = Ex.what();
ResponseCode = HttpResponseCode::InternalServerError;
}
Req.ServerRequest().WriteResponse(ResponseCode, HttpContentType::kText, FailureReason);
},
HttpVerb::kPost);
m_Router.RegisterRoute(
"modules/{moduleid}/deprovision",
[this](HttpRouterRequest& Req) {
std::string_view ModuleId = Req.GetCapture(1);
std::string FailureReason = "unknown";
try
{
if (!m_Impl->Deprovision(std::string(ModuleId), /* out */ FailureReason))
{
if (FailureReason.empty())
{
return Req.ServerRequest().WriteResponse(HttpResponseCode::NotFound);
}
else
{
return Req.ServerRequest().WriteResponse(HttpResponseCode::BadRequest, HttpContentType::kText, FailureReason);
}
}
CbObjectWriter Obj;
Obj << "moduleId" << ModuleId;
return Req.ServerRequest().WriteResponse(HttpResponseCode::OK, Obj.Save());
}
catch (const std::exception& Ex)
{
ZEN_ERROR("Exception while deprovisioning module '{}': {}", ModuleId, Ex.what());
FailureReason = Ex.what();
}
Req.ServerRequest().WriteResponse(HttpResponseCode::InternalServerError, HttpContentType::kText, FailureReason);
},
HttpVerb::kPost);
m_Router.RegisterRoute(
"stats",
[this](HttpRouterRequest& Req) {
CbObjectWriter Obj;
Obj << "currentInstanceCount" << m_Impl->GetInstanceCount();
Obj << "maxInstanceCount" << m_Impl->GetMaxInstanceCount();
Obj << "instanceLimit" << m_Impl->GetInstanceLimit();
Req.ServerRequest().WriteResponse(HttpResponseCode::OK);
},
HttpVerb::kGet);
}
HttpHubService::~HttpHubService()
{
}
const char*
HttpHubService::BaseUri() const
{
return "/hub/";
}
void
HttpHubService::SetNotificationEndpoint(std::string_view UpstreamNotificationEndpoint, std::string_view InstanceId)
{
ZEN_UNUSED(UpstreamNotificationEndpoint, InstanceId);
// TODO: store these for use in notifications, on some interval/criteria which is currently TBD
}
void
HttpHubService::HandleRequest(zen::HttpServerRequest& Request)
{
m_Router.HandleRequest(Request);
}
void
HttpHubService::HandleModuleGet(HttpServerRequest& Request, std::string_view ModuleId)
{
StorageServerInstance* Instance = nullptr;
if (!m_Impl->Find(ModuleId, &Instance))
{
Request.WriteResponse(HttpResponseCode::NotFound);
return;
}
CbObjectWriter Obj;
Obj << "moduleId" << Instance->GetModuleId();
Obj << "provisioned" << Instance->IsProvisioned();
Request.WriteResponse(HttpResponseCode::OK, Obj.Save());
}
void
HttpHubService::HandleModuleDelete(HttpServerRequest& Request, std::string_view ModuleId)
{
StorageServerInstance* Instance = nullptr;
if (!m_Impl->Find(ModuleId, &Instance))
{
Request.WriteResponse(HttpResponseCode::NotFound);
return;
}
// TODO: deprovision and nuke all related storage
CbObjectWriter Obj;
Obj << "moduleId" << Instance->GetModuleId();
Obj << "provisioned" << Instance->IsProvisioned();
Request.WriteResponse(HttpResponseCode::OK, Obj.Save());
}
} // namespace zen
|