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
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
|
// Copyright Epic Games, Inc. All Rights Reserved.
#include "config.h"
#include "config/luaconfig.h"
#include "diag/logging.h"
#include <zencore/basicfile.h>
#include <zencore/compactbinarybuilder.h>
#include <zencore/compactbinaryvalidation.h>
#include <zencore/crypto.h>
#include <zencore/except.h>
#include <zencore/fmtutils.h>
#include <zencore/iobuffer.h>
#include <zencore/logging.h>
#include <zencore/string.h>
#include <zenhttp/zenhttp.h>
#include <zenutil/commandlineoptions.h>
ZEN_THIRD_PARTY_INCLUDES_START
#include <fmt/format.h>
#include <fmt/ranges.h>
#include <zencore/logging.h>
#include <cxxopts.hpp>
#include <json11.hpp>
#include <sol/sol.hpp>
ZEN_THIRD_PARTY_INCLUDES_END
#if ZEN_PLATFORM_WINDOWS
# include <conio.h>
#else
# include <unistd.h>
#endif
#include <unordered_map>
#include <unordered_set>
namespace zen {
std::filesystem::path
PickDefaultStateDirectory(std::filesystem::path SystemRoot)
{
if (SystemRoot.empty())
return SystemRoot;
return SystemRoot / "Data";
}
void
EmitCentralManifest(const std::filesystem::path& SystemRoot, Oid Identifier, CbObject Manifest, std::filesystem::path ManifestPath)
{
CbObjectWriter Cbo;
Cbo << "path" << ManifestPath.generic_wstring();
Cbo << "manifest" << Manifest;
const std::filesystem::path StatesPath = SystemRoot / "States";
CreateDirectories(StatesPath);
WriteFile(StatesPath / fmt::format("{}", Identifier), Cbo.Save().GetBuffer().AsIoBuffer());
}
std::vector<CbObject>
ReadAllCentralManifests(const std::filesystem::path& SystemRoot)
{
std::vector<CbObject> Manifests;
DirectoryContent Content;
GetDirectoryContent(SystemRoot / "States", DirectoryContentFlags::IncludeFiles, Content);
for (std::filesystem::path& File : Content.Files)
{
try
{
FileContents FileData = ReadFile(File);
IoBuffer DataBuffer = FileData.Flatten();
CbValidateError ValidateError = ValidateCompactBinary(DataBuffer, CbValidateMode::All);
if (ValidateError == CbValidateError::None)
{
Manifests.push_back(LoadCompactBinaryObject(DataBuffer));
}
else
{
ZEN_WARN("failed to load manifest '{}': {}", File, ToString(ValidateError));
}
}
catch (const std::exception& Ex)
{
ZEN_WARN("failed to load manifest '{}': {}", File, Ex.what());
}
}
return Manifests;
}
void
ValidateOptions(ZenServerOptions& ServerOptions)
{
if (ServerOptions.EncryptionKey.empty() == false)
{
const auto Key = zen::AesKey256Bit::FromString(ServerOptions.EncryptionKey);
if (Key.IsValid() == false)
{
throw zen::OptionParseException("Invalid AES encryption key");
}
}
if (ServerOptions.EncryptionIV.empty() == false)
{
const auto IV = zen::AesIV128Bit::FromString(ServerOptions.EncryptionIV);
if (IV.IsValid() == false)
{
throw zen::OptionParseException("Invalid AES initialization vector");
}
}
if (ServerOptions.HttpServerConfig.ForceLoopback && ServerOptions.IsDedicated)
{
throw zen::OptionParseException("Dedicated server can not be used with forced local server address");
}
if (ServerOptions.GcConfig.AttachmentPassCount > ZenGcConfig::GcMaxAttachmentPassCount)
{
throw zen::OptionParseException(
fmt::format("GC attachment pass count can not be larger than {}", ZenGcConfig::GcMaxAttachmentPassCount));
}
if (ServerOptions.GcConfig.UseGCV2 == false)
{
ZEN_WARN("--gc-v2=false is deprecated, reverting to --gc-v2=true");
ServerOptions.GcConfig.UseGCV2 = true;
}
}
UpstreamCachePolicy
ParseUpstreamCachePolicy(std::string_view Options)
{
if (Options == "readonly")
{
return UpstreamCachePolicy::Read;
}
else if (Options == "writeonly")
{
return UpstreamCachePolicy::Write;
}
else if (Options == "disabled")
{
return UpstreamCachePolicy::Disabled;
}
else
{
return UpstreamCachePolicy::ReadWrite;
}
}
ZenObjectStoreConfig
ParseBucketConfigs(std::span<std::string> Buckets)
{
using namespace std::literals;
ZenObjectStoreConfig Cfg;
// split bucket args in the form of "{BucketName};{LocalPath}"
for (std::string_view Bucket : Buckets)
{
ZenObjectStoreConfig::BucketConfig NewBucket;
if (auto Idx = Bucket.find_first_of(";"); Idx != std::string_view::npos)
{
NewBucket.Name = Bucket.substr(0, Idx);
NewBucket.Directory = Bucket.substr(Idx + 1);
}
else
{
NewBucket.Name = Bucket;
}
Cfg.Buckets.push_back(std::move(NewBucket));
}
return Cfg;
}
class CachePolicyOption : public LuaConfig::OptionValue
{
public:
CachePolicyOption(UpstreamCachePolicy& Value) : Value(Value) {}
virtual void Print(std::string_view, zen::StringBuilderBase& StringBuilder) override
{
switch (Value)
{
case UpstreamCachePolicy::Read:
StringBuilder.Append("readonly");
break;
case UpstreamCachePolicy::Write:
StringBuilder.Append("writeonly");
break;
case UpstreamCachePolicy::Disabled:
StringBuilder.Append("disabled");
break;
case UpstreamCachePolicy::ReadWrite:
StringBuilder.Append("readwrite");
break;
default:
ZEN_ASSERT(false);
}
}
virtual void Parse(sol::object Object) override
{
std::string PolicyString = Object.as<std::string>();
if (PolicyString == "readonly")
{
Value = UpstreamCachePolicy::Read;
}
else if (PolicyString == "writeonly")
{
Value = UpstreamCachePolicy::Write;
}
else if (PolicyString == "disabled")
{
Value = UpstreamCachePolicy::Disabled;
}
else if (PolicyString == "readwrite")
{
Value = UpstreamCachePolicy::ReadWrite;
}
}
UpstreamCachePolicy& Value;
};
class ZenAuthConfigOption : public LuaConfig::OptionValue
{
public:
ZenAuthConfigOption(ZenAuthConfig& Value) : Value(Value) {}
virtual void Print(std::string_view Indent, zen::StringBuilderBase& StringBuilder) override
{
if (Value.OpenIdProviders.empty())
{
StringBuilder.Append("{}");
return;
}
LuaConfig::LuaContainerWriter Writer(StringBuilder, Indent);
for (const ZenOpenIdProviderConfig& Config : Value.OpenIdProviders)
{
Writer.BeginContainer("");
{
Writer.WriteValue("name", Config.Name);
Writer.WriteValue("url", Config.Url);
Writer.WriteValue("clientid", Config.ClientId);
}
Writer.EndContainer();
}
}
virtual void Parse(sol::object Object) override
{
if (sol::optional<sol::table> OpenIdProviders = Object.as<sol::table>())
{
for (const auto& Kv : OpenIdProviders.value())
{
if (sol::optional<sol::table> OpenIdProvider = Kv.second.as<sol::table>())
{
std::string Name = OpenIdProvider.value().get_or("name", std::string("Default"));
std::string Url = OpenIdProvider.value().get_or("url", std::string());
std::string ClientId = OpenIdProvider.value().get_or("clientid", std::string());
Value.OpenIdProviders.push_back({.Name = std::move(Name), .Url = std::move(Url), .ClientId = std::move(ClientId)});
}
}
}
}
ZenAuthConfig& Value;
};
class ZenObjectStoreConfigOption : public LuaConfig::OptionValue
{
public:
ZenObjectStoreConfigOption(ZenObjectStoreConfig& Value) : Value(Value) {}
virtual void Print(std::string_view Indent, zen::StringBuilderBase& StringBuilder) override
{
if (Value.Buckets.empty())
{
StringBuilder.Append("{}");
return;
}
LuaConfig::LuaContainerWriter Writer(StringBuilder, Indent);
for (const ZenObjectStoreConfig::BucketConfig& Config : Value.Buckets)
{
Writer.BeginContainer("");
{
Writer.WriteValue("name", Config.Name);
std::string Directory = Config.Directory.string();
LuaConfig::EscapeBackslash(Directory);
Writer.WriteValue("directory", Directory);
}
Writer.EndContainer();
}
}
virtual void Parse(sol::object Object) override
{
if (sol::optional<sol::table> Buckets = Object.as<sol::table>())
{
for (const auto& Kv : Buckets.value())
{
if (sol::optional<sol::table> Bucket = Kv.second.as<sol::table>())
{
std::string Name = Bucket.value().get_or("name", std::string("Default"));
std::string Directory = Bucket.value().get_or("directory", std::string());
Value.Buckets.push_back({.Name = std::move(Name), .Directory = MakeSafeAbsolutePath(Directory)});
}
}
}
}
ZenObjectStoreConfig& Value;
};
class ZenStructuredCacheBucketsConfigOption : public LuaConfig::OptionValue
{
public:
ZenStructuredCacheBucketsConfigOption(std::vector<std::pair<std::string, ZenStructuredCacheBucketConfig>>& Value) : Value(Value) {}
virtual void Print(std::string_view Indent, zen::StringBuilderBase& StringBuilder) override
{
if (Value.empty())
{
StringBuilder.Append("{}");
return;
}
LuaConfig::LuaContainerWriter Writer(StringBuilder, Indent);
for (const std::pair<std::string, ZenStructuredCacheBucketConfig>& Bucket : Value)
{
Writer.BeginContainer("");
{
Writer.WriteValue("name", Bucket.first);
const ZenStructuredCacheBucketConfig& BucketConfig = Bucket.second;
Writer.WriteValue("maxblocksize", fmt::format("{}", BucketConfig.MaxBlockSize));
Writer.BeginContainer("memlayer");
{
Writer.WriteValue("sizethreshold", fmt::format("{}", BucketConfig.MemCacheSizeThreshold));
}
Writer.EndContainer();
Writer.WriteValue("payloadalignment", fmt::format("{}", BucketConfig.PayloadAlignment));
Writer.WriteValue("largeobjectthreshold", fmt::format("{}", BucketConfig.PayloadAlignment));
}
Writer.EndContainer();
}
}
virtual void Parse(sol::object Object) override
{
if (sol::optional<sol::table> Buckets = Object.as<sol::table>())
{
for (const auto& Kv : Buckets.value())
{
if (sol::optional<sol::table> Bucket = Kv.second.as<sol::table>())
{
ZenStructuredCacheBucketConfig BucketConfig;
std::string Name = Kv.first.as<std::string>();
if (Name.empty())
{
throw zen::OptionParseException(fmt::format("cache bucket option must have a name."));
}
const uint64_t MaxBlockSize = Bucket.value().get_or("maxblocksize", BucketConfig.MaxBlockSize);
if (MaxBlockSize == 0)
{
throw zen::OptionParseException(
fmt::format("maxblocksize option for cache bucket '{}' is invalid. It must be non-zero.", Name));
}
BucketConfig.MaxBlockSize = MaxBlockSize;
if (sol::optional<sol::table> Memlayer = Bucket.value().get_or("memlayer", sol::table()))
{
const uint64_t MemCacheSizeThreshold = Bucket.value().get_or("sizethreshold", BucketConfig.MemCacheSizeThreshold);
if (MemCacheSizeThreshold == 0)
{
throw zen::OptionParseException(
fmt::format("memlayer.sizethreshold option for cache bucket '{}' is invalid. It must be non-zero.", Name));
}
BucketConfig.MemCacheSizeThreshold = Bucket.value().get_or("sizethreshold", BucketConfig.MemCacheSizeThreshold);
}
const uint32_t PayloadAlignment = Bucket.value().get_or("payloadalignment", BucketConfig.PayloadAlignment);
if (PayloadAlignment == 0 || !IsPow2(PayloadAlignment))
{
throw zen::OptionParseException(fmt::format(
"payloadalignment option for cache bucket '{}' is invalid. It needs to be non-zero and a power of two.",
Name));
}
BucketConfig.PayloadAlignment = PayloadAlignment;
const uint64_t LargeObjectThreshold = Bucket.value().get_or("largeobjectthreshold", BucketConfig.LargeObjectThreshold);
if (LargeObjectThreshold == 0)
{
throw zen::OptionParseException(
fmt::format("largeobjectthreshold option for cache bucket '{}' is invalid. It must be non-zero.", Name));
}
BucketConfig.LargeObjectThreshold = LargeObjectThreshold;
Value.push_back(std::make_pair(std::move(Name), BucketConfig));
}
}
}
}
std::vector<std::pair<std::string, ZenStructuredCacheBucketConfig>>& Value;
};
std::shared_ptr<LuaConfig::OptionValue>
MakeOption(zen::UpstreamCachePolicy& Value)
{
return std::make_shared<CachePolicyOption>(Value);
};
std::shared_ptr<LuaConfig::OptionValue>
MakeOption(zen::ZenAuthConfig& Value)
{
return std::make_shared<ZenAuthConfigOption>(Value);
};
std::shared_ptr<LuaConfig::OptionValue>
MakeOption(zen::ZenObjectStoreConfig& Value)
{
return std::make_shared<ZenObjectStoreConfigOption>(Value);
};
std::shared_ptr<LuaConfig::OptionValue>
MakeOption(std::vector<std::pair<std::string, ZenStructuredCacheBucketConfig>>& Value)
{
return std::make_shared<ZenStructuredCacheBucketsConfigOption>(Value);
};
void
ParseConfigFile(const std::filesystem::path& Path,
ZenServerOptions& ServerOptions,
const cxxopts::ParseResult& CmdLineResult,
std::string_view OutputConfigFile)
{
using namespace std::literals;
LuaConfig::Options LuaOptions;
////// server
LuaOptions.AddOption("server.dedicated"sv, ServerOptions.IsDedicated, "dedicated"sv);
LuaOptions.AddOption("server.logid"sv, ServerOptions.LogId, "log-id"sv);
LuaOptions.AddOption("server.sentry.disable"sv, ServerOptions.NoSentry, "no-sentry"sv);
LuaOptions.AddOption("server.sentry.allowpersonalinfo"sv, ServerOptions.SentryAllowPII, "sentry-allow-personal-info"sv);
LuaOptions.AddOption("server.systemrootdir"sv, ServerOptions.SystemRootDir, "system-dir"sv);
LuaOptions.AddOption("server.datadir"sv, ServerOptions.DataDir, "data-dir"sv);
LuaOptions.AddOption("server.contentdir"sv, ServerOptions.ContentDir, "content-dir"sv);
LuaOptions.AddOption("server.abslog"sv, ServerOptions.AbsLogFile, "abslog"sv);
LuaOptions.AddOption("server.pluginsconfigfile"sv, ServerOptions.PluginsConfigFile, "plugins-config"sv);
LuaOptions.AddOption("server.debug"sv, ServerOptions.IsDebug, "debug"sv);
LuaOptions.AddOption("server.clean"sv, ServerOptions.IsCleanStart, "clean"sv);
LuaOptions.AddOption("server.noconsole"sv, ServerOptions.NoConsoleOutput, "quiet"sv);
////// objectstore
LuaOptions.AddOption("server.objectstore.enabled"sv, ServerOptions.ObjectStoreEnabled, "objectstore-enabled"sv);
LuaOptions.AddOption("server.objectstore.buckets"sv, ServerOptions.ObjectStoreConfig);
////// buildsstore
LuaOptions.AddOption("server.buildstore.enabled"sv, ServerOptions.BuildStoreConfig.Enabled, "buildstore-enabled"sv);
LuaOptions.AddOption("server.buildstore.disksizelimit"sv, ServerOptions.BuildStoreConfig.MaxDiskSpaceLimit, "buildstore-disksizelimit");
////// network
LuaOptions.AddOption("network.httpserverclass"sv, ServerOptions.HttpServerConfig.ServerClass, "http"sv);
LuaOptions.AddOption("network.httpserverthreads"sv, ServerOptions.HttpServerConfig.ThreadCount, "http-threads"sv);
LuaOptions.AddOption("network.port"sv, ServerOptions.BasePort, "port"sv);
LuaOptions.AddOption("network.forceloopback"sv, ServerOptions.HttpServerConfig.ForceLoopback, "http-forceloopback"sv);
LuaOptions.AddOption("network.httpsys.async.workthreads"sv,
ServerOptions.HttpServerConfig.HttpSys.AsyncWorkThreadCount,
"httpsys-async-work-threads"sv);
LuaOptions.AddOption("network.httpsys.async.response"sv,
ServerOptions.HttpServerConfig.HttpSys.IsAsyncResponseEnabled,
"httpsys-enable-async-response"sv);
LuaOptions.AddOption("network.httpsys.requestlogging"sv,
ServerOptions.HttpServerConfig.HttpSys.IsRequestLoggingEnabled,
"httpsys-enable-request-logging"sv);
#if ZEN_WITH_TRACE
////// trace
LuaOptions.AddOption("trace.host"sv, ServerOptions.TraceHost, "tracehost"sv);
LuaOptions.AddOption("trace.file"sv, ServerOptions.TraceFile, "tracefile"sv);
#endif
////// stats
LuaOptions.AddOption("stats.enable"sv, ServerOptions.StatsConfig.Enabled, "statsd"sv);
LuaOptions.AddOption("stats.host"sv, ServerOptions.StatsConfig.StatsdHost);
LuaOptions.AddOption("stats.port"sv, ServerOptions.StatsConfig.StatsdPort);
////// cache
LuaOptions.AddOption("cache.enable"sv, ServerOptions.StructuredCacheConfig.Enabled);
LuaOptions.AddOption("cache.writelog"sv, ServerOptions.StructuredCacheConfig.WriteLogEnabled, "cache-write-log"sv);
LuaOptions.AddOption("cache.accesslog"sv, ServerOptions.StructuredCacheConfig.AccessLogEnabled, "cache-access-log"sv);
LuaOptions.AddOption("cache.memlayer.sizethreshold"sv,
ServerOptions.StructuredCacheConfig.BucketConfig.MemCacheSizeThreshold,
"cache-memlayer-sizethreshold"sv);
LuaOptions.AddOption("cache.memlayer.targetfootprint"sv,
ServerOptions.StructuredCacheConfig.MemTargetFootprintBytes,
"cache-memlayer-targetfootprint"sv);
LuaOptions.AddOption("cache.memlayer.triminterval"sv,
ServerOptions.StructuredCacheConfig.MemTrimIntervalSeconds,
"cache-memlayer-triminterval"sv);
LuaOptions.AddOption("cache.memlayer.maxage"sv, ServerOptions.StructuredCacheConfig.MemMaxAgeSeconds, "cache-memlayer-maxage"sv);
LuaOptions.AddOption("cache.bucket.maxblocksize"sv,
ServerOptions.StructuredCacheConfig.BucketConfig.MaxBlockSize,
"cache-bucket-maxblocksize"sv);
LuaOptions.AddOption("cache.bucket.memlayer.sizethreshold"sv,
ServerOptions.StructuredCacheConfig.BucketConfig.MemCacheSizeThreshold,
"cache-bucket-memlayer-sizethreshold"sv);
LuaOptions.AddOption("cache.bucket.payloadalignment"sv,
ServerOptions.StructuredCacheConfig.BucketConfig.PayloadAlignment,
"cache-bucket-payloadalignment"sv);
LuaOptions.AddOption("cache.bucket.largeobjectthreshold"sv,
ServerOptions.StructuredCacheConfig.BucketConfig.LargeObjectThreshold,
"cache-bucket-largeobjectthreshold"sv);
////// cache.upstream
LuaOptions.AddOption("cache.upstream.policy"sv, ServerOptions.UpstreamCacheConfig.CachePolicy, "upstream-cache-policy"sv);
LuaOptions.AddOption("cache.upstream.upstreamthreadcount"sv,
ServerOptions.UpstreamCacheConfig.UpstreamThreadCount,
"upstream-thread-count"sv);
LuaOptions.AddOption("cache.upstream.connecttimeoutms"sv,
ServerOptions.UpstreamCacheConfig.ConnectTimeoutMilliseconds,
"upstream-connect-timeout-ms"sv);
LuaOptions.AddOption("cache.upstream.timeoutms"sv, ServerOptions.UpstreamCacheConfig.TimeoutMilliseconds, "upstream-timeout-ms"sv);
////// cache.upstream.jupiter
LuaOptions.AddOption("cache.upstream.jupiter.name"sv, ServerOptions.UpstreamCacheConfig.JupiterConfig.Name);
LuaOptions.AddOption("cache.upstream.jupiter.url"sv, ServerOptions.UpstreamCacheConfig.JupiterConfig.Url, "upstream-jupiter-url"sv);
LuaOptions.AddOption("cache.upstream.jupiter.oauthprovider"sv,
ServerOptions.UpstreamCacheConfig.JupiterConfig.OAuthUrl,
"upstream-jupiter-oauth-url"sv);
LuaOptions.AddOption("cache.upstream.jupiter.oauthclientid"sv,
ServerOptions.UpstreamCacheConfig.JupiterConfig.OAuthClientId,
"upstream-jupiter-oauth-clientid");
LuaOptions.AddOption("cache.upstream.jupiter.oauthclientsecret"sv,
ServerOptions.UpstreamCacheConfig.JupiterConfig.OAuthClientSecret,
"upstream-jupiter-oauth-clientsecret"sv);
LuaOptions.AddOption("cache.upstream.jupiter.openidprovider"sv,
ServerOptions.UpstreamCacheConfig.JupiterConfig.OpenIdProvider,
"upstream-jupiter-openid-provider"sv);
LuaOptions.AddOption("cache.upstream.jupiter.token"sv,
ServerOptions.UpstreamCacheConfig.JupiterConfig.AccessToken,
"upstream-jupiter-token"sv);
LuaOptions.AddOption("cache.upstream.jupiter.namespace"sv,
ServerOptions.UpstreamCacheConfig.JupiterConfig.Namespace,
"upstream-jupiter-namespace"sv);
LuaOptions.AddOption("cache.upstream.jupiter.ddcnamespace"sv,
ServerOptions.UpstreamCacheConfig.JupiterConfig.DdcNamespace,
"upstream-jupiter-namespace-ddc"sv);
////// cache.upstream.zen
// LuaOptions.AddOption("cache.upstream.zen"sv, ServerOptions.UpstreamCacheConfig.ZenConfig);
LuaOptions.AddOption("cache.upstream.zen.name"sv, ServerOptions.UpstreamCacheConfig.ZenConfig.Name);
LuaOptions.AddOption("cache.upstream.zen.dns"sv, ServerOptions.UpstreamCacheConfig.ZenConfig.Dns);
LuaOptions.AddOption("cache.upstream.zen.url"sv, ServerOptions.UpstreamCacheConfig.ZenConfig.Urls);
////// gc
LuaOptions.AddOption("gc.enabled"sv, ServerOptions.GcConfig.Enabled, "gc-enabled"sv);
LuaOptions.AddOption("gc.v2"sv, ServerOptions.GcConfig.UseGCV2, "gc-v2"sv);
LuaOptions.AddOption("gc.monitorintervalseconds"sv, ServerOptions.GcConfig.MonitorIntervalSeconds, "gc-monitor-interval-seconds"sv);
LuaOptions.AddOption("gc.intervalseconds"sv, ServerOptions.GcConfig.IntervalSeconds, "gc-interval-seconds"sv);
LuaOptions.AddOption("gc.collectsmallobjects"sv, ServerOptions.GcConfig.CollectSmallObjects, "gc-small-objects"sv);
LuaOptions.AddOption("gc.diskreservesize"sv, ServerOptions.GcConfig.DiskReserveSize, "disk-reserve-size"sv);
LuaOptions.AddOption("gc.disksizesoftlimit"sv, ServerOptions.GcConfig.DiskSizeSoftLimit, "gc-disksize-softlimit"sv);
LuaOptions.AddOption("gc.lowdiskspacethreshold"sv,
ServerOptions.GcConfig.MinimumFreeDiskSpaceToAllowWrites,
"gc-low-diskspace-threshold"sv);
LuaOptions.AddOption("gc.lightweightintervalseconds"sv,
ServerOptions.GcConfig.LightweightIntervalSeconds,
"gc-lightweight-interval-seconds"sv);
LuaOptions.AddOption("gc.compactblockthreshold"sv,
ServerOptions.GcConfig.CompactBlockUsageThresholdPercent,
"gc-compactblock-threshold"sv);
LuaOptions.AddOption("gc.verbose"sv, ServerOptions.GcConfig.Verbose, "gc-verbose"sv);
LuaOptions.AddOption("gc.single-threaded"sv, ServerOptions.GcConfig.SingleThreaded, "gc-single-threaded"sv);
LuaOptions.AddOption("gc.cache.attachment.store"sv, ServerOptions.GcConfig.StoreCacheAttachmentMetaData, "gc-cache-attachment-store");
LuaOptions.AddOption("gc.projectstore.attachment.store"sv,
ServerOptions.GcConfig.StoreProjectAttachmentMetaData,
"gc-projectstore-attachment-store");
LuaOptions.AddOption("gc.attachment.passes"sv, ServerOptions.GcConfig.AttachmentPassCount, "gc-attachment-passes"sv);
LuaOptions.AddOption("gc.validation"sv, ServerOptions.GcConfig.EnableValidation, "gc-validation");
LuaOptions.AddOption("gc.cache.maxdurationseconds"sv, ServerOptions.GcConfig.Cache.MaxDurationSeconds, "gc-cache-duration-seconds"sv);
LuaOptions.AddOption("gc.projectstore.duration.seconds"sv,
ServerOptions.GcConfig.ProjectStore.MaxDurationSeconds,
"gc-projectstore-duration-seconds");
LuaOptions.AddOption("gc.buildstore.duration.seconds"sv,
ServerOptions.GcConfig.BuildStore.MaxDurationSeconds,
"gc-buildstore-duration-seconds");
////// security
LuaOptions.AddOption("security.encryptionaeskey"sv, ServerOptions.EncryptionKey, "encryption-aes-key"sv);
LuaOptions.AddOption("security.encryptionaesiv"sv, ServerOptions.EncryptionIV, "encryption-aes-iv"sv);
LuaOptions.AddOption("security.openidproviders"sv, ServerOptions.AuthConfig);
////// workspaces
LuaOptions.AddOption("workspaces.enabled"sv, ServerOptions.WorksSpacesConfig.Enabled, "workspaces-enabled"sv);
LuaOptions.AddOption("workspaces.allowconfigchanges"sv,
ServerOptions.WorksSpacesConfig.AllowConfigurationChanges,
"workspaces-allow-changes"sv);
LuaOptions.AddOption("cache.buckets"sv, ServerOptions.StructuredCacheConfig.PerBucketConfigs, "cache.buckets"sv);
LuaOptions.Parse(Path, CmdLineResult);
// These have special command line processing so we make sure we export them if they were configured on command line
if (!ServerOptions.AuthConfig.OpenIdProviders.empty())
{
LuaOptions.Touch("security.openidproviders"sv);
}
if (!ServerOptions.ObjectStoreConfig.Buckets.empty())
{
LuaOptions.Touch("server.objectstore.buckets"sv);
}
if (!ServerOptions.StructuredCacheConfig.PerBucketConfigs.empty())
{
LuaOptions.Touch("cache.buckets"sv);
}
if (!OutputConfigFile.empty())
{
std::filesystem::path WritePath(MakeSafeAbsolutePath(OutputConfigFile));
zen::ExtendableStringBuilder<512> ConfigStringBuilder;
LuaOptions.Print(ConfigStringBuilder, CmdLineResult);
zen::BasicFile Output;
Output.Open(WritePath, zen::BasicFile::Mode::kTruncate);
Output.Write(ConfigStringBuilder.Data(), ConfigStringBuilder.Size(), 0);
}
}
void
ParsePluginsConfigFile(const std::filesystem::path& Path, ZenServerOptions& ServerOptions, int BasePort)
{
using namespace std::literals;
IoBuffer Body = IoBufferBuilder::MakeFromFile(Path);
std::string JsonText(reinterpret_cast<const char*>(Body.GetData()), Body.GetSize());
std::string JsonError;
json11::Json PluginsInfo = json11::Json::parse(JsonText, JsonError);
if (!JsonError.empty())
{
ZEN_WARN("failed parsing plugins config file '{}'. Reason: '{}'", Path, JsonError);
return;
}
for (const json11::Json& PluginInfo : PluginsInfo.array_items())
{
if (!PluginInfo.is_object())
{
ZEN_WARN("the json file '{}' does not contain a valid plugin definition, object expected, got '{}'", Path, PluginInfo.dump());
continue;
}
HttpServerPluginConfig Config = {};
bool bNeedsPort = true;
for (const std::pair<const std::string, json11::Json>& Items : PluginInfo.object_items())
{
if (!Items.second.is_string())
{
ZEN_WARN("the json file '{}' does not contain a valid plugins definition, string expected, got '{}'",
Path,
Items.second.dump());
continue;
}
const std::string& Name = Items.first;
const std::string& Value = Items.second.string_value();
if (Name == "name"sv)
Config.PluginName = Value;
else
{
Config.PluginOptions.push_back({Name, Value});
if (Name == "port"sv)
{
bNeedsPort = false;
}
}
}
// add a default base port in case if json config didn't provide one
if (bNeedsPort)
{
Config.PluginOptions.push_back({"port", std::to_string(BasePort)});
}
ServerOptions.HttpServerConfig.PluginConfigs.push_back(Config);
}
}
void
ParseCliOptions(int argc, char* argv[], ZenServerOptions& ServerOptions)
{
const char* DefaultHttp = "asio";
#if ZEN_WITH_HTTPSYS
if (!zen::windows::IsRunningOnWine())
{
DefaultHttp = "httpsys";
}
#endif
for (int i = 0; i < argc; ++i)
{
if (i)
{
ServerOptions.CommandLine.push_back(' ');
}
ServerOptions.CommandLine += argv[i];
}
// Note to those adding future options; std::filesystem::path-type options
// must be read into a std::string first. As of cxxopts-3.0.0 it uses a >>
// stream operator to convert argv value into the options type. std::fs::path
// expects paths in streams to be quoted but argv paths are unquoted. By
// going into a std::string first, paths with whitespace parse correctly.
std::string SystemRootDir;
std::string DataDir;
std::string ContentDir;
std::string AbsLogFile;
std::string ConfigFile;
std::string PluginsConfigFile;
std::string OutputConfigFile;
std::string BaseSnapshotDir;
cxxopts::Options options("zenserver", "Zen Server");
options.add_options()("dedicated",
"Enable dedicated server mode",
cxxopts::value<bool>(ServerOptions.IsDedicated)->default_value("false"));
options.add_options()("d, debug", "Enable debugging", cxxopts::value<bool>(ServerOptions.IsDebug)->default_value("false"));
options.add_options()("clean",
"Clean out all state at startup",
cxxopts::value<bool>(ServerOptions.IsCleanStart)->default_value("false"));
options.add_options()("scrub",
"Validate state at startup",
cxxopts::value(ServerOptions.ScrubOptions)->implicit_value("yes"),
"(nocas,nogc,nodelete,yes,no)*");
options.add_options()("help", "Show command line help");
options.add_options()("t, test", "Enable test mode", cxxopts::value<bool>(ServerOptions.IsTest)->default_value("false"));
options.add_options()("data-dir", "Specify persistence root", cxxopts::value<std::string>(DataDir));
options.add_options()("system-dir", "Specify system root", cxxopts::value<std::string>(SystemRootDir));
options.add_options()("snapshot-dir",
"Specify a snapshot of server state to mirror into the persistence root at startup",
cxxopts::value<std::string>(BaseSnapshotDir));
options.add_options()("content-dir", "Frontend content directory", cxxopts::value<std::string>(ContentDir));
options.add_options()("powercycle",
"Exit immediately after initialization is complete",
cxxopts::value<bool>(ServerOptions.IsPowerCycle));
options.add_options()("config", "Path to Lua config file", cxxopts::value<std::string>(ConfigFile));
options.add_options()("plugins-config", "Path to plugins config file", cxxopts::value<std::string>(PluginsConfigFile));
options.add_options()("write-config", "Path to output Lua config file", cxxopts::value<std::string>(OutputConfigFile));
options.add_options()("no-sentry",
"Disable Sentry crash handler",
cxxopts::value<bool>(ServerOptions.NoSentry)->default_value("false"));
options.add_options()("sentry-allow-personal-info",
"Allow personally identifiable information in sentry crash reports",
cxxopts::value<bool>(ServerOptions.SentryAllowPII)->default_value("false"));
options.add_options()("detach",
"Indicate whether zenserver should detach from parent process group",
cxxopts::value<bool>(ServerOptions.Detach)->default_value("true"));
options.add_options()("malloc",
"Configure memory allocator subsystem",
cxxopts::value(ServerOptions.MemoryOptions)->default_value("mimalloc"));
// clang-format off
options.add_options("logging")
("abslog", "Path to log file", cxxopts::value<std::string>(AbsLogFile))
("log-id", "Specify id for adding context to log output", cxxopts::value<std::string>(ServerOptions.LogId))
("quiet", "Disable console logging", cxxopts::value<bool>(ServerOptions.NoConsoleOutput)->default_value("false"))
("log-trace", "Change selected loggers to level TRACE", cxxopts::value<std::string>(ServerOptions.Loggers[logging::level::Trace]))
("log-debug", "Change selected loggers to level DEBUG", cxxopts::value<std::string>(ServerOptions.Loggers[logging::level::Debug]))
("log-info", "Change selected loggers to level INFO", cxxopts::value<std::string>(ServerOptions.Loggers[logging::level::Info]))
("log-warn", "Change selected loggers to level WARN", cxxopts::value<std::string>(ServerOptions.Loggers[logging::level::Warn]))
("log-error", "Change selected loggers to level ERROR", cxxopts::value<std::string>(ServerOptions.Loggers[logging::level::Err]))
("log-critical", "Change selected loggers to level CRITICAL", cxxopts::value<std::string>(ServerOptions.Loggers[logging::level::Critical]))
("log-off", "Change selected loggers to level OFF", cxxopts::value<std::string>(ServerOptions.Loggers[logging::level::Off]))
;
// clang-format on
options.add_option("security",
"",
"encryption-aes-key",
"256 bit AES encryption key",
cxxopts::value<std::string>(ServerOptions.EncryptionKey),
"");
options.add_option("security",
"",
"encryption-aes-iv",
"128 bit AES encryption initialization vector",
cxxopts::value<std::string>(ServerOptions.EncryptionIV),
"");
std::string OpenIdProviderName;
options.add_option("security",
"",
"openid-provider-name",
"Open ID provider name",
cxxopts::value<std::string>(OpenIdProviderName),
"Default");
std::string OpenIdProviderUrl;
options.add_option("security", "", "openid-provider-url", "Open ID provider URL", cxxopts::value<std::string>(OpenIdProviderUrl), "");
std::string OpenIdClientId;
options.add_option("security", "", "openid-client-id", "Open ID client ID", cxxopts::value<std::string>(OpenIdClientId), "");
options
.add_option("lifetime", "", "owner-pid", "Specify owning process id", cxxopts::value<int>(ServerOptions.OwnerPid), "<identifier>");
options.add_option("lifetime",
"",
"child-id",
"Specify id which can be used to signal parent",
cxxopts::value<std::string>(ServerOptions.ChildId),
"<identifier>");
#if ZEN_PLATFORM_WINDOWS
options.add_option("lifetime",
"",
"install",
"Install zenserver as a Windows service",
cxxopts::value<bool>(ServerOptions.InstallService),
"");
options.add_option("lifetime",
"",
"uninstall",
"Uninstall zenserver as a Windows service",
cxxopts::value<bool>(ServerOptions.UninstallService),
"");
#endif
options.add_option("network",
"",
"http",
"Select HTTP server implementation (asio|httpsys|null)",
cxxopts::value<std::string>(ServerOptions.HttpServerConfig.ServerClass)->default_value(DefaultHttp),
"<http class>");
options.add_option("network",
"",
"http-threads",
"Number of http server connection threads",
cxxopts::value<unsigned int>(ServerOptions.HttpServerConfig.ThreadCount),
"<http threads>");
options.add_option("network",
"p",
"port",
"Select HTTP port",
cxxopts::value<int>(ServerOptions.BasePort)->default_value("8558"),
"<port number>");
options.add_option("network",
"",
"http-forceloopback",
"Force using local loopback interface",
cxxopts::value<bool>(ServerOptions.HttpServerConfig.ForceLoopback)->default_value("false"),
"<http forceloopback>");
options.add_option("httpsys",
"",
"httpsys-async-work-threads",
"Number of HttpSys async worker threads",
cxxopts::value<unsigned int>(ServerOptions.HttpServerConfig.HttpSys.AsyncWorkThreadCount),
"<httpsys workthreads>");
options.add_option("httpsys",
"",
"httpsys-enable-async-response",
"Enables Httpsys async response",
cxxopts::value<bool>(ServerOptions.HttpServerConfig.HttpSys.IsAsyncResponseEnabled)->default_value("true"),
"<httpsys async response>");
options.add_option("httpsys",
"",
"httpsys-enable-request-logging",
"Enables Httpsys request logging",
cxxopts::value<bool>(ServerOptions.HttpServerConfig.HttpSys.IsRequestLoggingEnabled),
"<httpsys request logging>");
#if ZEN_WITH_TRACE
options.add_option("ue-trace",
"",
"trace",
"Specify which trace channels should be enabled",
cxxopts::value<std::string>(ServerOptions.TraceChannels)->default_value(""),
"");
options.add_option("ue-trace",
"",
"tracehost",
"Hostname to send the trace to",
cxxopts::value<std::string>(ServerOptions.TraceHost)->default_value(""),
"");
options.add_option("ue-trace",
"",
"tracefile",
"Path to write a trace to",
cxxopts::value<std::string>(ServerOptions.TraceFile)->default_value(""),
"");
#endif // ZEN_WITH_TRACE
options.add_option("diagnostics",
"",
"crash",
"Simulate a crash",
cxxopts::value<bool>(ServerOptions.ShouldCrash)->default_value("false"),
"");
std::string UpstreamCachePolicyOptions;
options.add_option("cache",
"",
"upstream-cache-policy",
"",
cxxopts::value<std::string>(UpstreamCachePolicyOptions)->default_value(""),
"Upstream cache policy (readwrite|readonly|writeonly|disabled)");
options.add_option("cache",
"",
"upstream-jupiter-url",
"URL to a Jupiter instance",
cxxopts::value<std::string>(ServerOptions.UpstreamCacheConfig.JupiterConfig.Url)->default_value(""),
"");
options.add_option("cache",
"",
"upstream-jupiter-oauth-url",
"URL to the OAuth provier",
cxxopts::value<std::string>(ServerOptions.UpstreamCacheConfig.JupiterConfig.OAuthUrl)->default_value(""),
"");
options.add_option("cache",
"",
"upstream-jupiter-oauth-clientid",
"The OAuth client ID",
cxxopts::value<std::string>(ServerOptions.UpstreamCacheConfig.JupiterConfig.OAuthClientId)->default_value(""),
"");
options.add_option("cache",
"",
"upstream-jupiter-oauth-clientsecret",
"The OAuth client secret",
cxxopts::value<std::string>(ServerOptions.UpstreamCacheConfig.JupiterConfig.OAuthClientSecret)->default_value(""),
"");
options.add_option("cache",
"",
"upstream-jupiter-openid-provider",
"Name of a registered Open ID provider",
cxxopts::value<std::string>(ServerOptions.UpstreamCacheConfig.JupiterConfig.OpenIdProvider)->default_value(""),
"");
options.add_option("cache",
"",
"upstream-jupiter-token",
"A static authentication token",
cxxopts::value<std::string>(ServerOptions.UpstreamCacheConfig.JupiterConfig.AccessToken)->default_value(""),
"");
options.add_option("cache",
"",
"upstream-jupiter-namespace",
"The Common Blob Store API namespace",
cxxopts::value<std::string>(ServerOptions.UpstreamCacheConfig.JupiterConfig.Namespace)->default_value(""),
"");
options.add_option("cache",
"",
"upstream-jupiter-namespace-ddc",
"The lecacy DDC namespace",
cxxopts::value<std::string>(ServerOptions.UpstreamCacheConfig.JupiterConfig.DdcNamespace)->default_value(""),
"");
options.add_option("cache",
"",
"upstream-zen-url",
"URL to remote Zen server. Use a comma separated list to choose the one with the best latency.",
cxxopts::value<std::vector<std::string>>(ServerOptions.UpstreamCacheConfig.ZenConfig.Urls),
"");
options.add_option("cache",
"",
"upstream-zen-dns",
"DNS that resolves to one or more Zen server instance(s)",
cxxopts::value<std::vector<std::string>>(ServerOptions.UpstreamCacheConfig.ZenConfig.Dns),
"");
options.add_option("cache",
"",
"upstream-thread-count",
"Number of threads used for upstream procsssing",
cxxopts::value<int32_t>(ServerOptions.UpstreamCacheConfig.UpstreamThreadCount)->default_value("4"),
"");
options.add_option("cache",
"",
"upstream-connect-timeout-ms",
"Connect timeout in millisecond(s). Default 5000 ms.",
cxxopts::value<int32_t>(ServerOptions.UpstreamCacheConfig.ConnectTimeoutMilliseconds)->default_value("5000"),
"");
options.add_option("cache",
"",
"upstream-timeout-ms",
"Timeout in millisecond(s). Default 0 ms",
cxxopts::value<int32_t>(ServerOptions.UpstreamCacheConfig.TimeoutMilliseconds)->default_value("0"),
"");
options.add_option("cache",
"",
"cache-write-log",
"Whether cache write log is enabled",
cxxopts::value<bool>(ServerOptions.StructuredCacheConfig.WriteLogEnabled)->default_value("false"),
"");
options.add_option("cache",
"",
"cache-access-log",
"Whether cache access log is enabled",
cxxopts::value<bool>(ServerOptions.StructuredCacheConfig.AccessLogEnabled)->default_value("false"),
"");
options.add_option(
"cache",
"",
"cache-memlayer-sizethreshold",
"The largest size of a cache entry that may be cached in memory. Default set to 1024 (1 Kb). Set to 0 to disable memory caching. "
"Obsolete, replaced by `--cache-bucket-memlayer-sizethreshold`",
cxxopts::value<uint64_t>(ServerOptions.StructuredCacheConfig.BucketConfig.MemCacheSizeThreshold)->default_value("1024"),
"");
options.add_option("cache",
"",
"cache-memlayer-targetfootprint",
"Max allowed memory used by cache memory layer per namespace in bytes. Default set to 536870912 (512 Mb).",
cxxopts::value<uint64_t>(ServerOptions.StructuredCacheConfig.MemTargetFootprintBytes)->default_value("536870912"),
"");
options.add_option("cache",
"",
"cache-memlayer-triminterval",
"Minimum time between each attempt to trim cache memory layers in seconds. Default set to 60 (1 min).",
cxxopts::value<uint64_t>(ServerOptions.StructuredCacheConfig.MemTrimIntervalSeconds)->default_value("60"),
"");
options.add_option("cache",
"",
"cache-memlayer-maxage",
"Maximum age of payloads when trimming cache memory layers in seconds. Default set to 86400 (1 day).",
cxxopts::value<uint64_t>(ServerOptions.StructuredCacheConfig.MemMaxAgeSeconds)->default_value("86400"),
"");
options.add_option("cache",
"",
"cache-bucket-maxblocksize",
"Max size of cache bucket blocks. Default set to 1073741824 (1GB).",
cxxopts::value<uint64_t>(ServerOptions.StructuredCacheConfig.BucketConfig.MaxBlockSize)->default_value("1073741824"),
"");
options.add_option("cache",
"",
"cache-bucket-payloadalignment",
"Payload alignement for cache bucket blocks. Default set to 16.",
cxxopts::value<uint32_t>(ServerOptions.StructuredCacheConfig.BucketConfig.PayloadAlignment)->default_value("16"),
"");
options.add_option(
"cache",
"",
"cache-bucket-largeobjectthreshold",
"Threshold for storing cache bucket values as loose files. Default set to 131072 (128 KB).",
cxxopts::value<uint64_t>(ServerOptions.StructuredCacheConfig.BucketConfig.LargeObjectThreshold)->default_value("131072"),
"");
options.add_option(
"cache",
"",
"cache-bucket-memlayer-sizethreshold",
"The largest size of a cache entry that may be cached in memory. Default set to 1024 (1 Kb). Set to 0 to disable memory caching.",
cxxopts::value<uint64_t>(ServerOptions.StructuredCacheConfig.BucketConfig.MemCacheSizeThreshold)->default_value("1024"),
"");
options.add_option("gc",
"",
"gc-cache-attachment-store",
"Enable storing attachments referenced by a cache record in block store meta data.",
cxxopts::value<bool>(ServerOptions.GcConfig.StoreCacheAttachmentMetaData)->default_value("false"),
"");
options.add_option("gc",
"",
"gc-projectstore-attachment-store",
"Enable storing attachments referenced by project oplogs in meta data.",
cxxopts::value<bool>(ServerOptions.GcConfig.StoreProjectAttachmentMetaData)->default_value("false"),
"");
options.add_option("gc",
"",
"gc-validation",
"Enable validation of references after full GC.",
cxxopts::value<bool>(ServerOptions.GcConfig.EnableValidation)->default_value("true"),
"");
options.add_option("gc",
"",
"gc-enabled",
"Whether garbage collection is enabled or not.",
cxxopts::value<bool>(ServerOptions.GcConfig.Enabled)->default_value("true"),
"");
options.add_option("gc",
"",
"gc-v2",
"Use V2 of GC implementation or not.",
cxxopts::value<bool>(ServerOptions.GcConfig.UseGCV2)->default_value("true"),
"");
options.add_option("gc",
"",
"gc-small-objects",
"Whether garbage collection of small objects is enabled or not.",
cxxopts::value<bool>(ServerOptions.GcConfig.CollectSmallObjects)->default_value("true"),
"");
options.add_option("gc",
"",
"gc-interval-seconds",
"Garbage collection interval in seconds. Default set to 3600 (1 hour).",
cxxopts::value<int32_t>(ServerOptions.GcConfig.IntervalSeconds)->default_value("3600"),
"");
options.add_option("gc",
"",
"gc-lightweight-interval-seconds",
"Lightweight garbage collection interval in seconds. Default set to 900 (30 min).",
cxxopts::value<int32_t>(ServerOptions.GcConfig.LightweightIntervalSeconds)->default_value("900"),
"");
options.add_option("gc",
"",
"gc-cache-duration-seconds",
"Max duration in seconds before Z$ entries get evicted. Default set to 1209600 (2 weeks)",
cxxopts::value<int32_t>(ServerOptions.GcConfig.Cache.MaxDurationSeconds)->default_value("1209600"),
"");
options.add_option("gc",
"",
"gc-projectstore-duration-seconds",
"Max duration in seconds before project store entries get evicted. Default set to 1209600 (2 weeks)",
cxxopts::value<int32_t>(ServerOptions.GcConfig.ProjectStore.MaxDurationSeconds)->default_value("1209600"),
"");
options.add_option("gc",
"",
"gc-buildstore-duration-seconds",
"Max duration in seconds before build store entries get evicted. Default set to 604800 (1 week)",
cxxopts::value<int32_t>(ServerOptions.GcConfig.BuildStore.MaxDurationSeconds)->default_value("604800"),
"");
options.add_option("gc",
"",
"disk-reserve-size",
"Size of gc disk reserve in bytes. Default set to 268435456 (256 Mb). Set to zero to disable.",
cxxopts::value<uint64_t>(ServerOptions.GcConfig.DiskReserveSize)->default_value("268435456"),
"");
options.add_option("gc",
"",
"gc-monitor-interval-seconds",
"Garbage collection monitoring interval in seconds. Default set to 30 (30 seconds)",
cxxopts::value<int32_t>(ServerOptions.GcConfig.MonitorIntervalSeconds)->default_value("30"),
"");
options.add_option("gc",
"",
"gc-low-diskspace-threshold",
"Minimum free space on disk to allow writes to disk. Default set to 268435456 (256 Mb). Set to zero to disable.",
cxxopts::value<uint64_t>(ServerOptions.GcConfig.MinimumFreeDiskSpaceToAllowWrites)->default_value("268435456"),
"");
options.add_option("gc",
"",
"gc-disksize-softlimit",
"Garbage collection disk usage soft limit. Default set to 0 (Off).",
cxxopts::value<uint64_t>(ServerOptions.GcConfig.DiskSizeSoftLimit)->default_value("0"),
"");
options.add_option("gc",
"",
"gc-compactblock-threshold",
"Garbage collection - how much of a compact block should be used to skip compacting the block. 0 - compact only "
"empty eligible blocks, 100 - compact all non-full eligible blocks.",
cxxopts::value<uint32_t>(ServerOptions.GcConfig.CompactBlockUsageThresholdPercent)->default_value("60"),
"");
options.add_option("gc",
"",
"gc-verbose",
"Enable verbose logging for GC.",
cxxopts::value<bool>(ServerOptions.GcConfig.Verbose)->default_value("false"),
"");
options.add_option("gc",
"",
"gc-single-threaded",
"Force GC to run single threaded.",
cxxopts::value<bool>(ServerOptions.GcConfig.SingleThreaded)->default_value("false"),
"");
options.add_option("gc",
"",
"gc-attachment-passes",
"Limit the range of unreferenced attachments included in GC check by breaking it into passes. Default is one pass "
"which includes all the attachments.",
cxxopts::value<uint16_t>(ServerOptions.GcConfig.AttachmentPassCount)->default_value("1"),
"");
options.add_option("objectstore",
"",
"objectstore-enabled",
"Whether the object store is enabled or not.",
cxxopts::value<bool>(ServerOptions.ObjectStoreEnabled)->default_value("false"),
"");
std::vector<std::string> BucketConfigs;
options.add_option("objectstore",
"",
"objectstore-bucket",
"Object store bucket mappings.",
cxxopts::value<std::vector<std::string>>(BucketConfigs),
"");
options.add_option("buildstore",
"",
"buildstore-enabled",
"Whether the builds store is enabled or not.",
cxxopts::value<bool>(ServerOptions.BuildStoreConfig.Enabled)->default_value("false"),
"");
options.add_option("buildstore",
"",
"buildstore-disksizelimit",
"Max number of bytes before build store entries get evicted. Default set to 1099511627776 (1TB week)",
cxxopts::value<uint64_t>(ServerOptions.BuildStoreConfig.MaxDiskSpaceLimit)->default_value("1099511627776"),
"");
options.add_option("stats",
"",
"statsd",
"",
cxxopts::value<bool>(ServerOptions.StatsConfig.Enabled)->default_value("false"),
"Enable statsd reporter (localhost:8125)");
options.add_option("workspaces",
"",
"workspaces-enabled",
"",
cxxopts::value<bool>(ServerOptions.WorksSpacesConfig.Enabled)->default_value("true"),
"Enable workspaces support with folder sharing");
options.add_option("workspaces",
"",
"workspaces-allow-changes",
"",
cxxopts::value<bool>(ServerOptions.WorksSpacesConfig.AllowConfigurationChanges)->default_value("false"),
"Allow adding/modifying/deleting of workspace and shares via http endpoint");
try
{
cxxopts::ParseResult Result;
try
{
Result = options.parse(argc, argv);
}
catch (const std::exception& Ex)
{
throw zen::OptionParseException(Ex.what());
}
if (Result.count("help"))
{
ZEN_CONSOLE("{}", options.help());
#if ZEN_PLATFORM_WINDOWS
ZEN_CONSOLE("Press any key to exit!");
_getch();
#else
// Assume the user's in a terminal on all other platforms and that
// they'll use less/more/etc. if need be.
#endif
exit(0);
}
for (int i = 0; i < logging::level::LogLevelCount; ++i)
{
logging::ConfigureLogLevels(logging::level::LogLevel(i), ServerOptions.Loggers[i]);
}
logging::RefreshLogLevels();
ServerOptions.SystemRootDir = MakeSafeAbsolutePath(SystemRootDir);
ServerOptions.DataDir = MakeSafeAbsolutePath(DataDir);
ServerOptions.BaseSnapshotDir = MakeSafeAbsolutePath(BaseSnapshotDir);
ServerOptions.ContentDir = MakeSafeAbsolutePath(ContentDir);
ServerOptions.AbsLogFile = MakeSafeAbsolutePath(AbsLogFile);
ServerOptions.ConfigFile = MakeSafeAbsolutePath(ConfigFile);
ServerOptions.PluginsConfigFile = MakeSafeAbsolutePath(PluginsConfigFile);
ServerOptions.UpstreamCacheConfig.CachePolicy = ParseUpstreamCachePolicy(UpstreamCachePolicyOptions);
if (!BaseSnapshotDir.empty())
{
if (DataDir.empty())
throw zen::OptionParseException("You must explicitly specify a data directory when specifying a base snapshot");
if (!IsDir(ServerOptions.BaseSnapshotDir))
throw OptionParseException(fmt::format("Snapshot directory must be a directory: '{}", BaseSnapshotDir));
}
if (OpenIdProviderUrl.empty() == false)
{
if (OpenIdClientId.empty())
{
throw zen::OptionParseException("Invalid OpenID client ID");
}
ServerOptions.AuthConfig.OpenIdProviders.push_back(
{.Name = OpenIdProviderName, .Url = OpenIdProviderUrl, .ClientId = OpenIdClientId});
}
ServerOptions.ObjectStoreConfig = ParseBucketConfigs(BucketConfigs);
if (!ServerOptions.ConfigFile.empty())
{
ParseConfigFile(ServerOptions.ConfigFile, ServerOptions, Result, OutputConfigFile);
}
else
{
ParseConfigFile(ServerOptions.DataDir / "zen_cfg.lua", ServerOptions, Result, OutputConfigFile);
}
if (!ServerOptions.PluginsConfigFile.empty())
{
ParsePluginsConfigFile(ServerOptions.PluginsConfigFile, ServerOptions, ServerOptions.BasePort);
}
ValidateOptions(ServerOptions);
}
catch (const zen::OptionParseException& e)
{
ZEN_CONSOLE_ERROR("Error parsing zenserver arguments: {}\n\n{}", e.what(), options.help());
throw;
}
if (ServerOptions.SystemRootDir.empty())
{
ServerOptions.SystemRootDir = PickDefaultSystemRootDirectory();
}
if (ServerOptions.DataDir.empty())
{
ServerOptions.DataDir = PickDefaultStateDirectory(ServerOptions.SystemRootDir);
}
if (ServerOptions.AbsLogFile.empty())
{
ServerOptions.AbsLogFile = ServerOptions.DataDir / "logs" / "zenserver.log";
}
ServerOptions.HttpServerConfig.IsDedicatedServer = ServerOptions.IsDedicated;
}
} // namespace zen
|