Repository navigation
Expand file tree
/
Copy pathLoadGenerator.cpp
More file actions
1987 lines (1797 loc) · 66.2 KB
/
Copy pathLoadGenerator.cpp
File metadata and controls
1987 lines (1797 loc) · 66.2 KB
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
// Copyright 2015 Stellar Development Foundation and contributors. Licensed
// under the Apache License, Version 2.0. See the COPYING file at the root
// of this distribution or at http://www.apache.org/licenses/LICENSE-2.0
#include "simulation/LoadGenerator.h"
#include "database/Database.h"
#include "herder/Herder.h"
#include "ledger/LedgerManager.h"
#include "main/Config.h"
#include "overlay/OverlayManager.h"
#include "test/TestAccount.h"
#include "test/TxTests.h"
#include "transactions/MutableTransactionResult.h"
#include "transactions/TransactionBridge.h"
#include "transactions/TransactionUtils.h"
#include "transactions/test/SorobanTxTestUtils.h"
#include "util/Logging.h"
#include "util/Math.h"
#include "util/MetricsRegistry.h"
#include "util/Timer.h"
#include "util/XDRCereal.h"
#include "util/XDRStream.h"
#include "util/numeric.h"
#include "util/types.h"
#include "xdrpp/marshal.h"
#include "medida/meter.h"
#include "ledger/test/LedgerTestUtils.h"
#include <Tracy.hpp>
#include <cmath>
#include <crypto/SHA.h>
#include <fmt/format.h>
#include <iomanip>
#include <set>
namespace stellar
{
using namespace std;
using namespace txtest;
namespace
{
// Sample from a discrete distribution of `values` with weights `weights`.
// Returns `defaultValue` if `values` is empty.
template <typename T>
T
sampleDiscrete(std::vector<T> const& values,
std::vector<uint32_t> const& weights, T defaultValue)
{
if (values.empty())
{
return defaultValue;
}
std::discrete_distribution<uint32_t> distribution(weights.begin(),
weights.end());
return values.at(distribution(getGlobalRandomEngine()));
}
} // namespace
// Units of load are scheduled at 100ms intervals.
uint32_t const LoadGenerator::STEP_MSECS = 100;
// If submission fails with txBAD_SEQ, attempt refreshing the account or
// re-submitting a new payment
uint32_t const LoadGenerator::TX_SUBMIT_MAX_TRIES = 10;
// After successfully submitting desired load, wait a bit to let it get into the
// ledger.
uint32_t const LoadGenerator::TIMEOUT_NUM_LEDGERS = 20;
// After successfully submitting desired load, wait for this many ledgers
// without checking for account consistency.
uint32_t const LoadGenerator::COMPLETION_TIMEOUT_WITHOUT_CHECKS = 4;
// Minimum unique account multiplier. This is used to calculate the minimum
// number of accounts needed to sustain desired tx/s rate (this provides a
// buffer in case loadgen is unstable and needs more accounts)
uint32_t const LoadGenerator::MIN_UNIQUE_ACCOUNT_MULTIPLIER = 3;
static uint32_t
getTxCount(Application& app, bool isSoroban)
{
if (isSoroban)
{
return app.getMetrics()
.NewCounter({"herder", "pending-soroban-txs", "self-count"})
.count();
}
else
{
return app.getMetrics()
.NewCounter({"herder", "pending-txs", "self-count"})
.count();
}
}
static bool
isMixedPregenMode(LoadGenMode mode)
{
return mode == LoadGenMode::MIXED_PREGEN_SAC_PAYMENT ||
mode == LoadGenMode::MIXED_PREGEN_OZ_TOKEN_TRANSFER ||
mode == LoadGenMode::MIXED_PREGEN_SOROSWAP_SWAP;
}
LoadGenerator::LoadGenerator(Application& app)
: mTxGenerator(app)
, mApp(app)
, mLastSecond(0)
, mTotalSubmitted(0)
, mStepTimer(mApp.getMetrics().NewTimer({"loadgen", "step", "submit"}))
, mStepMeter(
mApp.getMetrics().NewMeter({"loadgen", "step", "count"}, "step"))
, mTxMetrics(app.getMetrics())
, mApplyTxTimer(
mApp.getMetrics().NewTimer({"ledger", "transaction", "apply"}))
, mApplyOpTimer(
mApp.getMetrics().NewTimer({"ledger", "operation", "apply"}))
, mRoot(app.getRoot())
, mLoadgenComplete(
mApp.getMetrics().NewMeter({"loadgen", "run", "complete"}, "run"))
, mLoadgenFail(
mApp.getMetrics().NewMeter({"loadgen", "run", "failed"}, "run"))
{
}
LoadGenMode
LoadGenerator::getMode(std::string const& mode)
{
if (mode == "pay")
{
return LoadGenMode::PAY;
}
else if (mode == "soroban_upload")
{
return LoadGenMode::SOROBAN_UPLOAD;
}
else if (mode == "soroban_invoke_setup")
{
return LoadGenMode::SOROBAN_INVOKE_SETUP;
}
else if (mode == "soroban_invoke")
{
return LoadGenMode::SOROBAN_INVOKE;
}
else if (mode == "upgrade_setup")
{
return LoadGenMode::SOROBAN_UPGRADE_SETUP;
}
else if (mode == "create_upgrade")
{
return LoadGenMode::SOROBAN_CREATE_UPGRADE;
}
else if (mode == "mixed_classic_soroban")
{
return LoadGenMode::MIXED_CLASSIC_SOROBAN;
}
else if (mode == "pay_pregenerated")
{
return LoadGenMode::PAY_PREGENERATED;
}
else if (mode == "mixed_pregen_sac_payment")
{
return LoadGenMode::MIXED_PREGEN_SAC_PAYMENT;
}
else if (mode == "mixed_pregen_oz_token_transfer")
{
return LoadGenMode::MIXED_PREGEN_OZ_TOKEN_TRANSFER;
}
else if (mode == "mixed_pregen_soroswap_swap")
{
return LoadGenMode::MIXED_PREGEN_SOROSWAP_SWAP;
}
else
{
throw std::runtime_error(
fmt::format(FMT_STRING("Unknown loadgen mode: {}"), mode));
}
}
std::optional<uint32_t>
LoadGenerator::chooseByteCount(Config const& cfg) const
{
if (cfg.LOADGEN_BYTE_COUNT_FOR_TESTING.size() == 0)
{
return std::nullopt;
}
return sampleDiscrete(cfg.LOADGEN_BYTE_COUNT_FOR_TESTING,
cfg.LOADGEN_BYTE_COUNT_DISTRIBUTION_FOR_TESTING, 0u);
}
int64_t
LoadGenerator::getTxPerStep(uint32_t txRate, std::chrono::seconds spikeInterval,
uint32_t spikeSize)
{
return getTxPerStep(txRate, spikeInterval, spikeSize, mTotalSubmitted);
}
int64_t
LoadGenerator::getTxPerStep(uint32_t txRate, std::chrono::seconds spikeInterval,
uint32_t spikeSize, uint64_t submittedSoFar)
{
if (!mStartTime)
{
throw std::runtime_error("Load generation start time must be set");
}
mStepMeter.Mark();
auto now = mApp.getClock().now();
auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
now - *mStartTime);
auto txs =
bigDivideOrThrow(elapsed.count(), txRate, 1000, Rounding::ROUND_DOWN);
if (spikeInterval.count() > 0)
{
txs += bigDivideOrThrow(
std::chrono::duration_cast<std::chrono::seconds>(elapsed)
.count(),
1, spikeInterval.count(), Rounding::ROUND_DOWN) *
spikeSize;
}
if (txs <= static_cast<int64_t>(submittedSoFar))
{
return 0;
}
return txs - static_cast<int64_t>(submittedSoFar);
}
void
LoadGenerator::cleanupAccounts()
{
ZoneScoped;
// "Free" any accounts that aren't used by the tx queue anymore
for (auto it = mAccountsInUse.begin(); it != mAccountsInUse.end();)
{
auto const& accounts = mTxGenerator.getAccounts();
auto accIt = accounts.find(*it);
releaseAssert(accIt != accounts.end());
if (!mApp.getHerder().sourceAccountPending(
accIt->second->getPublicKey()))
{
mAccountsAvailable.insert(*it);
it = mAccountsInUse.erase(it);
}
else
{
it++;
}
}
}
// Reset everything except Soroban persistent state
// Do not reset pregenerated transaction file position either
void
LoadGenerator::reset()
{
mTxGenerator.reset();
mAccountsInUse.clear();
mAccountsAvailable.clear();
mContractInstances.clear();
mLoadTimer.reset();
mStartTime.reset();
mTotalSubmitted = 0;
mClassicSubmitted = 0;
mSorobanSubmitted = 0;
mClassicAppliedAtStart = 0;
mSorobanAppliedAtStart = 0;
mSyntheticSACInstance.reset();
mSyntheticTokenInstance.reset();
mSyntheticSoroswapState.reset();
mSyntheticSACDestCounter = 0;
mSyntheticSoroswapSwapCounter = 0;
mWaitTillCompleteForLedgers = 0;
mFailed = false;
mStarted = false;
mPreLoadgenApplySorobanSuccess = 0;
mPreLoadgenApplySorobanFailure = 0;
}
// Reset Soroban persistent state
void
LoadGenerator::resetSorobanState()
{
mContractInstanceKeys.clear();
mCodeKey.reset();
mContactOverheadBytes = 0;
}
void
LoadGenerator::stop()
{
ZoneScoped;
if (mStarted)
{
// Some residual transactions might still be pending in consensus, but
// that should be harmless.
if (mLoadTimer)
{
mLoadTimer->cancel();
}
mLoadgenFail.Mark();
reset();
}
}
void
LoadGenerator::start(GeneratedLoadConfig& cfg)
{
if (mStarted)
{
return;
}
mClassicAppliedAtStart = getTxCount(mApp, /* isSoroban */ false);
mSorobanAppliedAtStart = getTxCount(mApp, /* isSoroban */ true);
if (cfg.modeMixesPregen() && !mApp.getRunInOverlayOnlyMode())
{
reset();
throw std::runtime_error(
"Can only run SOROBAN_INVOKE_APPLY_LOAD / MIXED_PREGEN_* modes in "
"overlay only mode");
}
if (cfg.txRate == 0)
{
cfg.txRate = 1;
}
// Setup config for soroban modes
if (cfg.isSoroban() && cfg.mode != LoadGenMode::SOROBAN_UPLOAD)
{
auto& sorobanLoadCfg = cfg.getMutSorobanConfig();
sorobanLoadCfg.nWasms = 1;
if (cfg.mode == LoadGenMode::SOROBAN_UPGRADE_SETUP)
{
// Only deploy single upgrade contract instance
sorobanLoadCfg.nInstances = 1;
}
if (cfg.mode == LoadGenMode::SOROBAN_CREATE_UPGRADE)
{
// Submit a single upgrade TX
sorobanLoadCfg.nInstances = 1;
cfg.nTxs = 1;
}
if (cfg.isSorobanSetup())
{
resetSorobanState();
// For first round of txs, we need to deploy the wasms.
// waitTillFinished will set nTxs for instances once wasms have been
// verified
cfg.nTxs = sorobanLoadCfg.nWasms;
// Must include all TXs
cfg.skipLowFeeTxs = false;
// No spikes during setup
cfg.spikeInterval = std::chrono::seconds(0);
cfg.spikeSize = 0;
}
if (cfg.modeSetsUpInvoke() || cfg.modeInvokes())
{
// Default instances to 1
if (sorobanLoadCfg.nInstances == 0)
{
sorobanLoadCfg.nInstances = 1;
}
}
}
if (cfg.mode != LoadGenMode::PAY_PREGENERATED)
{
// For upgrade modes, use root account (represented by special ID)
uint32_t accounts = cfg.nAccounts;
if (cfg.mode == LoadGenMode::SOROBAN_UPGRADE_SETUP ||
cfg.mode == LoadGenMode::SOROBAN_CREATE_UPGRADE)
{
mAccountsAvailable.insert(TxGenerator::ROOT_ACCOUNT_ID);
if (accounts)
{
accounts--;
}
}
// Mark all accounts "available" as source accounts
for (auto i = 0u; i < accounts; i++)
{
mAccountsAvailable.insert(i + cfg.offset);
}
if (cfg.modeInvokes())
{
auto const& sorobanLoadCfg = cfg.getSorobanConfig();
if (!mCodeKey)
{
// start is incomplete, so reset to avoid leaving the
// LoadGenerator in an invalid state.
reset();
throw std::runtime_error(
"Before running MODE::SOROBAN_INVOKE, please run "
"MODE::SOROBAN_INVOKE_SETUP to set up your contract "
"first.");
}
releaseAssert(mContractInstances.empty());
releaseAssert(mAccountsAvailable.size() >= cfg.nAccounts);
releaseAssert(mContractInstanceKeys.size() >=
sorobanLoadCfg.nInstances);
releaseAssert(cfg.nAccounts >= sorobanLoadCfg.nInstances);
// assign a contract instance to each accountID
auto accountIter = mAccountsAvailable.begin();
for (size_t i = 0; i < cfg.nAccounts; ++i)
{
auto instanceKeyIter = mContractInstanceKeys.begin();
std::advance(instanceKeyIter, i % sorobanLoadCfg.nInstances);
TxGenerator::ContractInstance instance;
instance.readOnlyKeys.emplace_back(*mCodeKey);
instance.readOnlyKeys.emplace_back(*instanceKeyIter);
instance.contractID = instanceKeyIter->contractData().contract;
mContractInstances.emplace(*accountIter, instance);
++accountIter;
}
}
}
releaseAssert(!mLoadTimer);
mLoadTimer = std::make_unique<VirtualTimer>(mApp.getClock());
releaseAssert(!mStartTime);
mStartTime =
std::make_unique<VirtualClock::time_point>(mApp.getClock().now());
releaseAssert(mPreLoadgenApplySorobanSuccess == 0);
releaseAssert(mPreLoadgenApplySorobanFailure == 0);
mPreLoadgenApplySorobanSuccess =
mTxGenerator.getApplySorobanSuccess().count();
mPreLoadgenApplySorobanFailure =
mTxGenerator.getApplySorobanFailure().count();
if (cfg.mode == LoadGenMode::PAY_PREGENERATED || cfg.modeMixesPregen())
{
if (!mPreloadedTransactionsFile)
{
mPreloadedTransactionsFile = XDRInputFileStream();
mPreloadedTransactionsFile->open(cfg.preloadedTransactionsFile);
}
// Preload all accounts
for (auto i = 0u; i < cfg.nAccounts; i++)
{
auto actualId = i + cfg.offset;
mTxGenerator.addAccount(
actualId, std::make_shared<TestAccount>(
mApp,
txtest::getAccount("TestAccount-" +
std::to_string(actualId)),
0));
}
}
mApp.getLedgerManager().beginTxLatencyMeasurement(cfg.nTxs);
mStarted = true;
}
ConfigUpgradeSetKey
LoadGenerator::getConfigUpgradeSetKey(
SorobanUpgradeConfig const& upgradeCfg) const
{
auto testingKeys = getContractInstanceKeysForTesting();
releaseAssert(testingKeys.size() == 1);
auto contractId = testingKeys.begin()->contractData().contract.contractId();
return mTxGenerator.getConfigUpgradeSetKey(upgradeCfg, contractId);
}
// Schedule a callback to generateLoad() STEP_MSECS milliseconds from now.
void
LoadGenerator::scheduleLoadGeneration(GeneratedLoadConfig cfg)
{
std::optional<std::string> errorMsg;
// If previously scheduled step of load did not succeed, fail this loadgen
// run.
if (mFailed)
{
errorMsg = "Load generation failed, ensure correct "
"number parameters are set and accounts are "
"created, or retry with smaller tx rate.";
}
// During load submission, we must have enough unique source accounts (with
// a buffer) to accommodate the desired tx rate.
auto closeTimeSeconds = std::chrono::duration_cast<std::chrono::seconds>(
mApp.getLedgerManager().getExpectedLedgerCloseTime());
if (cfg.nTxs > cfg.nAccounts && (cfg.txRate * closeTimeSeconds.count()) *
MIN_UNIQUE_ACCOUNT_MULTIPLIER >
cfg.nAccounts)
{
errorMsg = fmt::format(
"Tx rate is too high, there are not enough unique accounts. Make "
"sure there are at least {}x "
"unique accounts than desired number of transactions per ledger.",
MIN_UNIQUE_ACCOUNT_MULTIPLIER);
}
if (cfg.isSoroban() &&
protocolVersionIsBefore(mApp.getLedgerManager()
.getLastClosedLedgerHeader()
.header.ledgerVersion,
SOROBAN_PROTOCOL_VERSION))
{
errorMsg = "Soroban modes require protocol version 20 or higher";
}
if (cfg.modeInvokes())
{
auto const& sorobanLoadCfg = cfg.getSorobanConfig();
releaseAssertOrThrow(sorobanLoadCfg.nInstances != 0);
if (mContractInstanceKeys.size() < sorobanLoadCfg.nInstances ||
!mCodeKey)
{
errorMsg = "must run SOROBAN_INVOKE_SETUP with at least nInstances";
}
else if (cfg.nAccounts < sorobanLoadCfg.nInstances)
{
errorMsg = "must have more accounts than instances";
}
}
if (cfg.mode == LoadGenMode::SOROBAN_CREATE_UPGRADE)
{
if (mContractInstanceKeys.size() != 1 || !mCodeKey)
{
errorMsg = "must run SOROBAN_UPGRADE_SETUP";
}
}
if (cfg.mode == LoadGenMode::PAY_PREGENERATED || cfg.modeMixesPregen())
{
if (mApp.getConfig().GENESIS_TEST_ACCOUNT_COUNT == 0)
{
errorMsg = "PAY_PREGENERATED / MIXED_PREGEN_* modes require "
"non-zero GENESIS_TEST_ACCOUNT_COUNT";
}
else if (cfg.preloadedTransactionsFile.empty())
{
errorMsg = "PAY_PREGENERATED / MIXED_PREGEN_* modes require "
"preloadedTransactionsFile";
}
}
if (errorMsg)
{
CLOG_ERROR(LoadGen, "{}", *errorMsg);
mLoadgenFail.Mark();
reset();
if (cfg.isSorobanSetup())
{
resetSorobanState();
}
return;
}
if (mApp.getState() == Application::APP_SYNCED_STATE)
{
mLoadTimer->expires_from_now(std::chrono::milliseconds(STEP_MSECS));
mLoadTimer->async_wait([this, cfg]() { this->generateLoad(cfg); },
&VirtualTimer::onFailureNoop);
}
else
{
CLOG_WARNING(
LoadGen,
"Application is not in sync, load generation inhibited. State {}",
mApp.getStateHuman());
mLoadTimer->expires_from_now(std::chrono::seconds(10));
mLoadTimer->async_wait(
[this, cfg]() { this->scheduleLoadGeneration(cfg); },
&VirtualTimer::onFailureNoop);
}
}
bool
GeneratedLoadConfig::isDone() const
{
return (isLoad() && nTxs == 0) ||
(isSorobanSetup() && getSorobanConfig().nInstances == 0);
}
bool
GeneratedLoadConfig::areTxsRemaining() const
{
return nTxs != 0;
}
Json::Value
GeneratedLoadConfig::getStatus() const
{
Json::Value ret;
std::string modeStr;
switch (mode)
{
case LoadGenMode::PAY:
modeStr = "pay";
break;
case LoadGenMode::SOROBAN_UPLOAD:
modeStr = "soroban_upload";
break;
case LoadGenMode::SOROBAN_INVOKE_SETUP:
modeStr = "soroban_invoke_setup";
break;
case LoadGenMode::SOROBAN_INVOKE:
modeStr = "soroban_invoke";
break;
case LoadGenMode::SOROBAN_UPGRADE_SETUP:
modeStr = "upgrade_setup";
break;
case LoadGenMode::SOROBAN_CREATE_UPGRADE:
modeStr = "create_upgrade";
break;
case LoadGenMode::MIXED_CLASSIC_SOROBAN:
modeStr = "mixed_classic_soroban";
break;
case LoadGenMode::PAY_PREGENERATED:
modeStr = "pay_pregenerated";
break;
case LoadGenMode::MIXED_PREGEN_SAC_PAYMENT:
modeStr = "mixed_pregen_sac_payment";
break;
case LoadGenMode::MIXED_PREGEN_OZ_TOKEN_TRANSFER:
modeStr = "mixed_pregen_oz_token_transfer";
break;
case LoadGenMode::MIXED_PREGEN_SOROSWAP_SWAP:
modeStr = "mixed_pregen_soroswap_swap";
break;
}
ret["mode"] = modeStr;
if (isSorobanSetup())
{
ret["wasms_remaining"] = getSorobanConfig().nWasms;
ret["instances_remaining"] = getSorobanConfig().nInstances;
}
else
{
ret["txs_remaining"] = nTxs;
}
ret["tx_rate"] = std::to_string(txRate) + " tx/s";
if (modeInvokes())
{
ret["instances"] = getSorobanConfig().nInstances;
ret["wasms"] = getSorobanConfig().nWasms;
}
if (mode == LoadGenMode::MIXED_CLASSIC_SOROBAN)
{
auto const& blendCfg = getMixClassicSorobanConfig();
ret["pay_weight"] = blendCfg.payWeight;
ret["soroban_upload_weight"] = blendCfg.sorobanUploadWeight;
ret["soroban_invoke_weight"] = blendCfg.sorobanInvokeWeight;
}
if (isSoroban())
{
ret["min_soroban_percent_success"] = mMinSorobanPercentSuccess;
}
return ret;
}
// Generate one "step" worth of load (assuming 1 step per STEP_MSECS) at a
// given target number of accounts and txs, and a given target tx/s rate.
// If work remains after the current step, call scheduleLoadGeneration()
// with the remainder.
void
LoadGenerator::generateLoad(GeneratedLoadConfig cfg)
{
ZoneScoped;
start(cfg);
// Finish if no more txs need to be created.
if (!cfg.areTxsRemaining())
{
// Done submitting the load, now ensure it propagates to the DB.
if (cfg.skipLowFeeTxs)
{
// skipLowFeeTxs allows triggering tx queue limiter, which
// makes it hard to track the final seq nums. Hence just
// wait unconditionally.
waitTillCompleteWithoutChecks();
}
else
{
waitTillComplete(cfg);
}
return;
}
// For MIXED_PREGEN_* modes, classic and soroban streams have independent
// TPS. Compute per-step budgets from per-stream submitted counters so one
// stream's output doesn't starve the other (mTotalSubmitted is shared).
int64_t mixedClassicBudget = 0;
int64_t mixedSorobanBudget = 0;
if (cfg.modeMixesPregen())
{
auto const& mix = cfg.getMixPregenSorobanConfig();
mixedClassicBudget = getTxPerStep(mix.classicTxRate, cfg.spikeInterval,
cfg.spikeSize, mClassicSubmitted);
mixedSorobanBudget = getTxPerStep(mix.sorobanTxRate, cfg.spikeInterval,
cfg.spikeSize, mSorobanSubmitted);
}
auto txPerStep =
cfg.modeMixesPregen()
? (mixedClassicBudget + mixedSorobanBudget)
: getTxPerStep(cfg.txRate, cfg.spikeInterval, cfg.spikeSize);
auto submitScope = mStepTimer.TimeScope();
uint64_t now = mApp.timeNow();
// Cleaning up accounts every second, so we don't call potentially expensive
// cleanup function too often
if (now != mLastSecond && cfg.mode != LoadGenMode::PAY_PREGENERATED)
{
cleanupAccounts();
}
uint32_t ledgerNum = mApp.getLedgerManager().getLastClosedLedgerNum() + 1;
uint32_t count = 0;
for (int64_t i = 0; i < txPerStep; ++i)
{
if (mAccountsAvailable.empty() &&
cfg.mode != LoadGenMode::PAY_PREGENERATED && !cfg.modeMixesPregen())
{
CLOG_WARNING(LoadGen,
"Load generation failed: no more accounts available");
mLoadgenFail.Mark();
reset();
return;
}
uint64_t sourceAccountId = 0;
if (cfg.mode != LoadGenMode::PAY_PREGENERATED && !cfg.modeMixesPregen())
{
sourceAccountId = getNextAvailableAccount(ledgerNum);
}
std::function<std::pair<TxGenerator::TestAccountPtr,
TransactionFrameBaseConstPtr>()>
generateTx;
// Set by the MIXED_PREGEN_* lambda so the outer loop can bump the
// correct per-stream submitted counter after a successful submit.
bool isMixedSorobanTx = false;
switch (cfg.mode)
{
case LoadGenMode::PAY:
{
auto byteCount = chooseByteCount(mApp.getConfig());
generateTx = [&, byteCount]() {
return mTxGenerator.paymentTransaction(
cfg.nAccounts, cfg.offset, ledgerNum, sourceAccountId,
byteCount, cfg.maxGeneratedFeeRate);
};
}
break;
case LoadGenMode::SOROBAN_UPLOAD:
{
generateTx = [&]() {
return mTxGenerator.sorobanRandomWasmTransaction(
ledgerNum, sourceAccountId,
mTxGenerator.generateFee(cfg.maxGeneratedFeeRate,
/* opsCnt */ 1));
};
}
break;
case LoadGenMode::SOROBAN_INVOKE_SETUP:
case LoadGenMode::SOROBAN_UPGRADE_SETUP:
generateTx = [&] {
auto& sorobanCfg = cfg.getMutSorobanConfig();
if (sorobanCfg.nWasms != 0)
{
--sorobanCfg.nWasms;
return createUploadWasmTransaction(cfg, ledgerNum,
sourceAccountId);
}
else
{
--sorobanCfg.nInstances;
return createInstanceTransaction(cfg, ledgerNum,
sourceAccountId);
}
};
break;
case LoadGenMode::SOROBAN_INVOKE:
generateTx = [&]() {
auto instanceIter = mContractInstances.find(sourceAccountId);
releaseAssert(instanceIter != mContractInstances.end());
auto const& instance = instanceIter->second;
return mTxGenerator.invokeSorobanLoadTransaction(
ledgerNum, sourceAccountId, instance, mContactOverheadBytes,
cfg.maxGeneratedFeeRate);
};
break;
case LoadGenMode::SOROBAN_CREATE_UPGRADE:
generateTx = [&]() {
releaseAssert(mCodeKey);
releaseAssert(mContractInstanceKeys.size() == 1);
auto upgradeBytes =
mTxGenerator.getConfigUpgradeSetFromLoadConfig(
cfg.getSorobanUpgradeConfig());
return mTxGenerator.invokeSorobanCreateUpgradeTransaction(
ledgerNum, sourceAccountId, upgradeBytes, *mCodeKey,
*mContractInstanceKeys.begin(), cfg.maxGeneratedFeeRate);
};
break;
case LoadGenMode::MIXED_CLASSIC_SOROBAN:
{
auto byteCount = chooseByteCount(mApp.getConfig());
generateTx = [&, byteCount]() {
return createMixedClassicSorobanTransaction(
ledgerNum, sourceAccountId, byteCount, cfg);
};
}
break;
case LoadGenMode::PAY_PREGENERATED:
generateTx = [&]() { return readTransactionFromFile(cfg); };
break;
case LoadGenMode::MIXED_PREGEN_SAC_PAYMENT:
case LoadGenMode::MIXED_PREGEN_OZ_TOKEN_TRANSFER:
case LoadGenMode::MIXED_PREGEN_SOROSWAP_SWAP:
generateTx = [&]() {
// Soroban stream drained first each step, then classic.
if (mixedSorobanBudget > 0)
{
if (mAccountsAvailable.empty())
{
throw std::runtime_error(
"Load generation failed: no more accounts "
"available for soroban stream");
}
--mixedSorobanBudget;
isMixedSorobanTx = true;
uint64_t srcId = getNextAvailableAccount(ledgerNum);
return createSyntheticSorobanTransaction(ledgerNum, srcId,
cfg);
}
releaseAssert(mixedClassicBudget > 0);
--mixedClassicBudget;
isMixedSorobanTx = false;
return readTransactionFromFile(cfg);
};
break;
}
try
{
if (submitTx(cfg, generateTx))
{
--cfg.nTxs;
// Mixed modes decide per-tx via the lambda; other modes are
// classified by the mode as a whole.
bool isSorobanTx =
cfg.modeMixesPregen() ? isMixedSorobanTx : cfg.isSoroban();
if (isSorobanTx)
{
++mSorobanSubmitted;
}
else
{
++mClassicSubmitted;
}
}
}
catch (std::runtime_error const& e)
{
CLOG_ERROR(LoadGen, "Exception while submitting tx: {}", e.what());
mFailed = true;
break;
}
if (mFailed)
{
break;
}
++count;
if (cfg.nAccounts == 0 || !cfg.areTxsRemaining())
{
// Nothing to do for the rest of the step
break;
}
}
auto submit = submitScope.Stop();
now = mApp.timeNow();
// Emit a log message once per second.
if (now != mLastSecond)
{
logProgress(submit, cfg);
}
mLastSecond = now;
mTotalSubmitted += count;
scheduleLoadGeneration(cfg);
}
bool
LoadGenerator::submitTx(GeneratedLoadConfig const& cfg,
std::function<std::pair<TxGenerator::TestAccountPtr,
TransactionFrameBaseConstPtr>()>
generateTx)
{
auto [from, tx] = generateTx();
TransactionResultCode code;
TransactionQueue::AddResultCode status;
uint32_t numTries = 0;
while ((status = execute(tx, cfg.mode, code)) !=
TransactionQueue::AddResultCode::ADD_STATUS_PENDING)
{
if (cfg.mode != LoadGenMode::PAY_PREGENERATED && cfg.skipLowFeeTxs &&
(status ==
TransactionQueue::AddResultCode::ADD_STATUS_TRY_AGAIN_LATER ||
(status == TransactionQueue::AddResultCode::ADD_STATUS_ERROR &&
code == txINSUFFICIENT_FEE)))
{
// Rollback the seq num of the test account as we regenerate the
// transaction.
from->setSequenceNumber(from->getLastSequenceNumber() - 1);
CLOG_INFO(LoadGen, "skipped low fee tx with fee {}",
tx->getInclusionFee());
return false;
}
// No re-submission in PAY_PREGENERATED / MIXED_PREGEN_* modes.
// Each transaction is for a unique source account, so we
// should not see BAD_SEQ error codes unless core is actually dropping
// txs due to overload (in which case we should just fail loadgen,
// instead of re-submitting)
if (++numTries >= TX_SUBMIT_MAX_TRIES ||
status != TransactionQueue::AddResultCode::ADD_STATUS_ERROR ||
cfg.mode == LoadGenMode::PAY_PREGENERATED || cfg.modeMixesPregen())
{
mFailed = true;
return false;
}
// In case of bad seqnum, attempt refreshing it from the DB
maybeHandleFailedTx(tx, from, status, code); // Update seq num
// Regenerate a new payment tx
std::tie(from, tx) = generateTx();
}
return true;
}
uint64_t
LoadGenerator::getNextAvailableAccount(uint32_t ledgerNum)
{
uint64_t sourceAccountId;
do
{
releaseAssert(!mAccountsAvailable.empty());
auto sourceAccountIdx =
rand_uniform<uint64_t>(0, mAccountsAvailable.size() - 1);
auto it = mAccountsAvailable.begin();
std::advance(it, sourceAccountIdx);
sourceAccountId = *it;
mAccountsAvailable.erase(it);
releaseAssert(mAccountsInUse.insert(sourceAccountId).second);
// Although mAccountsAvailable shouldn't contain pending accounts, it is
// possible when the network is overloaded. Consider the following
// scenario:
// 1. This node generates a transaction `t` using account `a` and
// broadcasts it on. In doing so, loadgen marks `a` as in use,
// removing it from `mAccountsAvailable.
// 2. For whatever reason, `t` never makes it out of the queue and this
// node bans it.