cmCTestMultiProcessHandler.cxx 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #include "cmCTestMultiProcessHandler.h"
  4. #include <algorithm>
  5. #include <cassert>
  6. #include <chrono>
  7. #include <cmath>
  8. #include <cstddef> // IWYU pragma: keep
  9. #include <cstdlib>
  10. #include <cstring>
  11. #include <iomanip>
  12. #include <iostream>
  13. #include <list>
  14. #include <sstream>
  15. #include <stack>
  16. #include <unordered_map>
  17. #include <utility>
  18. #include <vector>
  19. #include <cm/memory>
  20. #include <cm/optional>
  21. #include <cmext/algorithm>
  22. #include <cm3p/json/value.h>
  23. #include <cm3p/json/writer.h>
  24. #include <cm3p/uv.h>
  25. #include "cmsys/FStream.hxx"
  26. #include "cmsys/SystemInformation.hxx"
  27. #include "cmAffinity.h"
  28. #include "cmCTest.h"
  29. #include "cmCTestBinPacker.h"
  30. #include "cmCTestRunTest.h"
  31. #include "cmCTestTestHandler.h"
  32. #include "cmDuration.h"
  33. #include "cmJSONState.h"
  34. #include "cmListFileCache.h"
  35. #include "cmRange.h"
  36. #include "cmStringAlgorithms.h"
  37. #include "cmSystemTools.h"
  38. #include "cmUVSignalHackRAII.h" // IWYU pragma: keep
  39. #include "cmWorkingDirectory.h"
  40. namespace cmsys {
  41. class RegularExpression;
  42. }
  43. class TestComparator
  44. {
  45. public:
  46. TestComparator(cmCTestMultiProcessHandler* handler)
  47. : Handler(handler)
  48. {
  49. }
  50. // Sorts tests in descending order of cost
  51. bool operator()(int index1, int index2) const
  52. {
  53. return this->Handler->Properties[index1]->Cost >
  54. this->Handler->Properties[index2]->Cost;
  55. }
  56. private:
  57. cmCTestMultiProcessHandler* Handler;
  58. };
  59. cmCTestMultiProcessHandler::cmCTestMultiProcessHandler()
  60. {
  61. this->ParallelLevel = 1;
  62. this->TestLoad = 0;
  63. this->FakeLoadForTesting = 0;
  64. this->Completed = 0;
  65. this->RunningCount = 0;
  66. this->ProcessorsAvailable = cmAffinity::GetProcessorsAvailable();
  67. this->HaveAffinity = this->ProcessorsAvailable.size();
  68. this->HasCycles = false;
  69. this->HasInvalidGeneratedResourceSpec = false;
  70. this->SerialTestRunning = false;
  71. }
  72. cmCTestMultiProcessHandler::~cmCTestMultiProcessHandler() = default;
  73. // Set the tests
  74. void cmCTestMultiProcessHandler::SetTests(TestMap tests,
  75. PropertiesMap properties)
  76. {
  77. this->PendingTests = std::move(tests);
  78. this->Properties = std::move(properties);
  79. this->Total = this->PendingTests.size();
  80. if (!this->CTest->GetShowOnly()) {
  81. this->ReadCostData();
  82. this->HasCycles = !this->CheckCycles();
  83. this->HasInvalidGeneratedResourceSpec =
  84. !this->CheckGeneratedResourceSpec();
  85. if (this->HasCycles || this->HasInvalidGeneratedResourceSpec) {
  86. return;
  87. }
  88. this->CreateTestCostList();
  89. }
  90. }
  91. // Set the max number of tests that can be run at the same time.
  92. void cmCTestMultiProcessHandler::SetParallelLevel(size_t level)
  93. {
  94. this->ParallelLevel = level < 1 ? 1 : level;
  95. }
  96. void cmCTestMultiProcessHandler::SetTestLoad(unsigned long load)
  97. {
  98. this->TestLoad = load;
  99. std::string fake_load_value;
  100. if (cmSystemTools::GetEnv("__CTEST_FAKE_LOAD_AVERAGE_FOR_TESTING",
  101. fake_load_value)) {
  102. if (!cmStrToULong(fake_load_value, &this->FakeLoadForTesting)) {
  103. cmSystemTools::Error("Failed to parse fake load value: " +
  104. fake_load_value);
  105. }
  106. }
  107. }
  108. bool cmCTestMultiProcessHandler::Complete()
  109. {
  110. return this->Completed == this->Total;
  111. }
  112. void cmCTestMultiProcessHandler::RunTests()
  113. {
  114. this->CheckResume();
  115. if (this->HasCycles || this->HasInvalidGeneratedResourceSpec) {
  116. return;
  117. }
  118. #ifdef CMAKE_UV_SIGNAL_HACK
  119. cmUVSignalHackRAII hackRAII;
  120. #endif
  121. this->TestHandler->SetMaxIndex(this->FindMaxIndex());
  122. this->Loop.init();
  123. this->StartNextTests();
  124. uv_run(this->Loop, UV_RUN_DEFAULT);
  125. this->Loop.reset();
  126. if (!this->StopTimePassed && !this->CheckStopOnFailure()) {
  127. assert(this->Complete());
  128. assert(this->PendingTests.empty());
  129. }
  130. assert(this->AllResourcesAvailable());
  131. this->MarkFinished();
  132. this->UpdateCostData();
  133. }
  134. bool cmCTestMultiProcessHandler::StartTestProcess(int test)
  135. {
  136. if (this->HaveAffinity && this->Properties[test]->WantAffinity) {
  137. size_t needProcessors = this->GetProcessorsUsed(test);
  138. assert(needProcessors <= this->ProcessorsAvailable.size());
  139. std::vector<size_t> affinity;
  140. affinity.reserve(needProcessors);
  141. for (size_t i = 0; i < needProcessors; ++i) {
  142. auto p = this->ProcessorsAvailable.begin();
  143. affinity.push_back(*p);
  144. this->ProcessorsAvailable.erase(p);
  145. }
  146. this->Properties[test]->Affinity = std::move(affinity);
  147. }
  148. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  149. "test " << test << "\n", this->Quiet);
  150. // now remove the test itself
  151. this->ErasePendingTest(test);
  152. this->RunningCount += this->GetProcessorsUsed(test);
  153. auto testRun = cm::make_unique<cmCTestRunTest>(*this, test);
  154. if (this->RepeatMode != cmCTest::Repeat::Never) {
  155. testRun->SetRepeatMode(this->RepeatMode);
  156. testRun->SetNumberOfRuns(this->RepeatCount);
  157. }
  158. if (this->UseResourceSpec) {
  159. testRun->SetUseAllocatedResources(true);
  160. testRun->SetAllocatedResources(this->AllocatedResources[test]);
  161. }
  162. // Find any failed dependencies for this test. We assume the more common
  163. // scenario has no failed tests, so make it the outer loop.
  164. for (std::string const& f : *this->Failed) {
  165. if (cm::contains(this->Properties[test]->RequireSuccessDepends, f)) {
  166. testRun->AddFailedDependency(f);
  167. }
  168. }
  169. // Always lock the resources we'll be using, even if we fail to set the
  170. // working directory because FinishTestProcess() will try to unlock them
  171. this->LockResources(test);
  172. if (!this->ResourceAllocationErrors[test].empty()) {
  173. std::ostringstream e;
  174. e << "Insufficient resources for test " << this->Properties[test]->Name
  175. << ":\n\n";
  176. for (auto const& it : this->ResourceAllocationErrors[test]) {
  177. switch (it.second) {
  178. case ResourceAllocationError::NoResourceType:
  179. e << " Test requested resources of type '" << it.first
  180. << "' which does not exist\n";
  181. break;
  182. case ResourceAllocationError::InsufficientResources:
  183. e << " Test requested resources of type '" << it.first
  184. << "' in the following amounts:\n";
  185. for (auto const& group : this->Properties[test]->ResourceGroups) {
  186. for (auto const& requirement : group) {
  187. if (requirement.ResourceType == it.first) {
  188. e << " " << requirement.SlotsNeeded
  189. << (requirement.SlotsNeeded == 1 ? " slot\n" : " slots\n");
  190. }
  191. }
  192. }
  193. e << " but only the following units were available:\n";
  194. for (auto const& res :
  195. this->ResourceAllocator.GetResources().at(it.first)) {
  196. e << " '" << res.first << "': " << res.second.Total
  197. << (res.second.Total == 1 ? " slot\n" : " slots\n");
  198. }
  199. break;
  200. }
  201. e << "\n";
  202. }
  203. e << "Resource spec file:\n\n " << this->ResourceSpecFile;
  204. cmCTestRunTest::StartFailure(std::move(testRun), this->Total, e.str(),
  205. "Insufficient resources");
  206. return false;
  207. }
  208. cmWorkingDirectory workdir(this->Properties[test]->Directory);
  209. if (workdir.Failed()) {
  210. cmCTestRunTest::StartFailure(std::move(testRun), this->Total,
  211. "Failed to change working directory to " +
  212. this->Properties[test]->Directory + " : " +
  213. std::strerror(workdir.GetLastResult()),
  214. "Failed to change working directory");
  215. return false;
  216. }
  217. // Ownership of 'testRun' has moved to another structure.
  218. // When the test finishes, FinishTestProcess will be called.
  219. return cmCTestRunTest::StartTest(std::move(testRun), this->Completed,
  220. this->Total);
  221. }
  222. bool cmCTestMultiProcessHandler::AllocateResources(int index)
  223. {
  224. if (!this->UseResourceSpec) {
  225. return true;
  226. }
  227. std::map<std::string, std::vector<cmCTestBinPackerAllocation>> allocations;
  228. if (!this->TryAllocateResources(index, allocations)) {
  229. return false;
  230. }
  231. auto& allocatedResources = this->AllocatedResources[index];
  232. allocatedResources.resize(this->Properties[index]->ResourceGroups.size());
  233. for (auto const& it : allocations) {
  234. for (auto const& alloc : it.second) {
  235. bool result = this->ResourceAllocator.AllocateResource(
  236. it.first, alloc.Id, alloc.SlotsNeeded);
  237. (void)result;
  238. assert(result);
  239. allocatedResources[alloc.ProcessIndex][it.first].push_back(
  240. { alloc.Id, static_cast<unsigned int>(alloc.SlotsNeeded) });
  241. }
  242. }
  243. return true;
  244. }
  245. bool cmCTestMultiProcessHandler::TryAllocateResources(
  246. int index,
  247. std::map<std::string, std::vector<cmCTestBinPackerAllocation>>& allocations,
  248. std::map<std::string, ResourceAllocationError>* errors)
  249. {
  250. allocations.clear();
  251. std::size_t processIndex = 0;
  252. for (auto const& process : this->Properties[index]->ResourceGroups) {
  253. for (auto const& requirement : process) {
  254. for (int i = 0; i < requirement.UnitsNeeded; ++i) {
  255. allocations[requirement.ResourceType].push_back(
  256. { processIndex, requirement.SlotsNeeded, "" });
  257. }
  258. }
  259. ++processIndex;
  260. }
  261. bool result = true;
  262. auto const& availableResources = this->ResourceAllocator.GetResources();
  263. for (auto& it : allocations) {
  264. if (!availableResources.count(it.first)) {
  265. if (errors) {
  266. (*errors)[it.first] = ResourceAllocationError::NoResourceType;
  267. result = false;
  268. } else {
  269. return false;
  270. }
  271. } else if (!cmAllocateCTestResourcesRoundRobin(
  272. availableResources.at(it.first), it.second)) {
  273. if (errors) {
  274. (*errors)[it.first] = ResourceAllocationError::InsufficientResources;
  275. result = false;
  276. } else {
  277. return false;
  278. }
  279. }
  280. }
  281. return result;
  282. }
  283. void cmCTestMultiProcessHandler::DeallocateResources(int index)
  284. {
  285. if (!this->UseResourceSpec) {
  286. return;
  287. }
  288. {
  289. auto& allocatedResources = this->AllocatedResources[index];
  290. for (auto const& processAlloc : allocatedResources) {
  291. for (auto const& it : processAlloc) {
  292. auto resourceType = it.first;
  293. for (auto const& it2 : it.second) {
  294. bool success = this->ResourceAllocator.DeallocateResource(
  295. resourceType, it2.Id, it2.Slots);
  296. (void)success;
  297. assert(success);
  298. }
  299. }
  300. }
  301. }
  302. this->AllocatedResources.erase(index);
  303. }
  304. bool cmCTestMultiProcessHandler::AllResourcesAvailable()
  305. {
  306. for (auto const& it : this->ResourceAllocator.GetResources()) {
  307. for (auto const& it2 : it.second) {
  308. if (it2.second.Locked != 0) {
  309. return false;
  310. }
  311. }
  312. }
  313. return true;
  314. }
  315. void cmCTestMultiProcessHandler::CheckResourcesAvailable()
  316. {
  317. if (this->UseResourceSpec) {
  318. for (auto test : this->OrderedTests) {
  319. std::map<std::string, std::vector<cmCTestBinPackerAllocation>>
  320. allocations;
  321. this->TryAllocateResources(test, allocations,
  322. &this->ResourceAllocationErrors[test]);
  323. }
  324. }
  325. }
  326. bool cmCTestMultiProcessHandler::CheckStopOnFailure()
  327. {
  328. return this->CTest->GetStopOnFailure();
  329. }
  330. bool cmCTestMultiProcessHandler::CheckStopTimePassed()
  331. {
  332. if (!this->StopTimePassed) {
  333. std::chrono::system_clock::time_point stop_time =
  334. this->CTest->GetStopTime();
  335. if (stop_time != std::chrono::system_clock::time_point() &&
  336. stop_time <= std::chrono::system_clock::now()) {
  337. this->SetStopTimePassed();
  338. }
  339. }
  340. return this->StopTimePassed;
  341. }
  342. void cmCTestMultiProcessHandler::SetStopTimePassed()
  343. {
  344. if (!this->StopTimePassed) {
  345. cmCTestLog(this->CTest, ERROR_MESSAGE,
  346. "The stop time has been passed. "
  347. "Stopping all tests."
  348. << std::endl);
  349. this->StopTimePassed = true;
  350. }
  351. }
  352. void cmCTestMultiProcessHandler::LockResources(int index)
  353. {
  354. this->LockedResources.insert(
  355. this->Properties[index]->LockedResources.begin(),
  356. this->Properties[index]->LockedResources.end());
  357. if (this->Properties[index]->RunSerial) {
  358. this->SerialTestRunning = true;
  359. }
  360. }
  361. void cmCTestMultiProcessHandler::UnlockResources(int index)
  362. {
  363. for (std::string const& i : this->Properties[index]->LockedResources) {
  364. this->LockedResources.erase(i);
  365. }
  366. if (this->Properties[index]->RunSerial) {
  367. this->SerialTestRunning = false;
  368. }
  369. }
  370. void cmCTestMultiProcessHandler::ErasePendingTest(int test)
  371. {
  372. this->PendingTests.erase(test);
  373. this->OrderedTests.erase(
  374. std::find(this->OrderedTests.begin(), this->OrderedTests.end(), test));
  375. }
  376. inline size_t cmCTestMultiProcessHandler::GetProcessorsUsed(int test)
  377. {
  378. size_t processors = static_cast<int>(this->Properties[test]->Processors);
  379. // If processors setting is set higher than the -j
  380. // setting, we default to using all of the process slots.
  381. if (processors > this->ParallelLevel) {
  382. processors = this->ParallelLevel;
  383. }
  384. // Cap tests that want affinity to the maximum affinity available.
  385. if (this->HaveAffinity && processors > this->HaveAffinity &&
  386. this->Properties[test]->WantAffinity) {
  387. processors = this->HaveAffinity;
  388. }
  389. return processors;
  390. }
  391. std::string cmCTestMultiProcessHandler::GetName(int test)
  392. {
  393. return this->Properties[test]->Name;
  394. }
  395. bool cmCTestMultiProcessHandler::StartTest(int test)
  396. {
  397. // Check for locked resources
  398. for (std::string const& i : this->Properties[test]->LockedResources) {
  399. if (cm::contains(this->LockedResources, i)) {
  400. return false;
  401. }
  402. }
  403. // Allocate resources
  404. if (this->ResourceAllocationErrors[test].empty() &&
  405. !this->AllocateResources(test)) {
  406. this->DeallocateResources(test);
  407. return false;
  408. }
  409. // if there are no depends left then run this test
  410. if (this->PendingTests[test].Depends.empty()) {
  411. return this->StartTestProcess(test);
  412. }
  413. // This test was not able to start because it is waiting
  414. // on depends to run
  415. this->DeallocateResources(test);
  416. return false;
  417. }
  418. void cmCTestMultiProcessHandler::StartNextTests()
  419. {
  420. if (this->TestLoadRetryTimer.get() != nullptr) {
  421. // This timer may be waiting to call StartNextTests again.
  422. // Since we have been called it is no longer needed.
  423. uv_timer_stop(this->TestLoadRetryTimer);
  424. }
  425. if (this->PendingTests.empty()) {
  426. this->TestLoadRetryTimer.reset();
  427. return;
  428. }
  429. if (this->CheckStopTimePassed()) {
  430. return;
  431. }
  432. if (this->CheckStopOnFailure() && !this->Failed->empty()) {
  433. return;
  434. }
  435. size_t numToStart = 0;
  436. if (this->RunningCount < this->ParallelLevel) {
  437. numToStart = this->ParallelLevel - this->RunningCount;
  438. }
  439. if (numToStart == 0) {
  440. return;
  441. }
  442. // Don't start any new tests if one with the RUN_SERIAL property
  443. // is already running.
  444. if (this->SerialTestRunning) {
  445. return;
  446. }
  447. bool allTestsFailedTestLoadCheck = false;
  448. size_t minProcessorsRequired = this->ParallelLevel;
  449. std::string testWithMinProcessors;
  450. cmsys::SystemInformation info;
  451. unsigned long systemLoad = 0;
  452. size_t spareLoad = 0;
  453. if (this->TestLoad > 0) {
  454. // Activate possible wait.
  455. allTestsFailedTestLoadCheck = true;
  456. // Check for a fake load average value used in testing.
  457. if (this->FakeLoadForTesting > 0) {
  458. systemLoad = this->FakeLoadForTesting;
  459. // Drop the fake load for the next iteration to a value low enough
  460. // that the next iteration will start tests.
  461. this->FakeLoadForTesting = 1;
  462. }
  463. // If it's not set, look up the true load average.
  464. else {
  465. systemLoad = static_cast<unsigned long>(ceil(info.GetLoadAverage()));
  466. }
  467. spareLoad =
  468. (this->TestLoad > systemLoad ? this->TestLoad - systemLoad : 0);
  469. // Don't start more tests than the spare load can support.
  470. if (numToStart > spareLoad) {
  471. numToStart = spareLoad;
  472. }
  473. }
  474. // Start tests in the preferred order, each subject to readiness checks.
  475. auto ti = this->OrderedTests.begin();
  476. while (ti != this->OrderedTests.end()) {
  477. // Increment the test iterator now because the current list
  478. // entry may be deleted below.
  479. int test = *ti++;
  480. // Take a nap if we're currently performing a RUN_SERIAL test.
  481. if (this->SerialTestRunning) {
  482. break;
  483. }
  484. // We can only start a RUN_SERIAL test if no other tests are also
  485. // running.
  486. if (this->Properties[test]->RunSerial && this->RunningCount > 0) {
  487. continue;
  488. }
  489. size_t processors = this->GetProcessorsUsed(test);
  490. bool testLoadOk = true;
  491. if (this->TestLoad > 0) {
  492. if (processors <= spareLoad) {
  493. cmCTestLog(this->CTest, DEBUG,
  494. "OK to run " << this->GetName(test) << ", it requires "
  495. << processors << " procs & system load is: "
  496. << systemLoad << std::endl);
  497. allTestsFailedTestLoadCheck = false;
  498. } else {
  499. testLoadOk = false;
  500. }
  501. }
  502. if (processors <= minProcessorsRequired) {
  503. minProcessorsRequired = processors;
  504. testWithMinProcessors = this->GetName(test);
  505. }
  506. if (testLoadOk && processors <= numToStart && this->StartTest(test)) {
  507. numToStart -= processors;
  508. } else if (numToStart == 0) {
  509. break;
  510. }
  511. }
  512. if (allTestsFailedTestLoadCheck) {
  513. // Find out whether there are any non RUN_SERIAL tests left, so that the
  514. // correct warning may be displayed.
  515. bool onlyRunSerialTestsLeft = true;
  516. for (auto const& test : this->OrderedTests) {
  517. if (!this->Properties[test]->RunSerial) {
  518. onlyRunSerialTestsLeft = false;
  519. }
  520. }
  521. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, "***** WAITING, ");
  522. if (this->SerialTestRunning) {
  523. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  524. "Waiting for RUN_SERIAL test to finish.");
  525. } else if (onlyRunSerialTestsLeft) {
  526. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  527. "Only RUN_SERIAL tests remain, awaiting available slot.");
  528. } else {
  529. /* clang-format off */
  530. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  531. "System Load: " << systemLoad << ", "
  532. "Max Allowed Load: " << this->TestLoad << ", "
  533. "Smallest test " << testWithMinProcessors <<
  534. " requires " << minProcessorsRequired);
  535. /* clang-format on */
  536. }
  537. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, "*****" << std::endl);
  538. // Wait between 1 and 5 seconds before trying again.
  539. unsigned int milliseconds = (cmSystemTools::RandomSeed() % 5 + 1) * 1000;
  540. if (this->FakeLoadForTesting) {
  541. milliseconds = 10;
  542. }
  543. if (this->TestLoadRetryTimer.get() == nullptr) {
  544. this->TestLoadRetryTimer.init(*this->Loop, this);
  545. }
  546. this->TestLoadRetryTimer.start(
  547. &cmCTestMultiProcessHandler::OnTestLoadRetryCB, milliseconds, 0);
  548. }
  549. }
  550. void cmCTestMultiProcessHandler::OnTestLoadRetryCB(uv_timer_t* timer)
  551. {
  552. auto* self = static_cast<cmCTestMultiProcessHandler*>(timer->data);
  553. self->StartNextTests();
  554. }
  555. void cmCTestMultiProcessHandler::FinishTestProcess(
  556. std::unique_ptr<cmCTestRunTest> runner, bool started)
  557. {
  558. this->Completed++;
  559. int test = runner->GetIndex();
  560. auto* properties = runner->GetTestProperties();
  561. cmCTestRunTest::EndTestResult testResult =
  562. runner->EndTest(this->Completed, this->Total, started);
  563. if (testResult.StopTimePassed) {
  564. this->SetStopTimePassed();
  565. }
  566. if (started) {
  567. if (!this->StopTimePassed &&
  568. cmCTestRunTest::StartAgain(std::move(runner), this->Completed)) {
  569. this->Completed--; // remove the completed test because run again
  570. return;
  571. }
  572. }
  573. if (testResult.Passed) {
  574. this->Passed->push_back(properties->Name);
  575. } else if (!properties->Disabled) {
  576. this->Failed->push_back(properties->Name);
  577. }
  578. for (auto& t : this->PendingTests) {
  579. t.second.Depends.erase(test);
  580. }
  581. this->WriteCheckpoint(test);
  582. this->DeallocateResources(test);
  583. this->UnlockResources(test);
  584. this->RunningCount -= this->GetProcessorsUsed(test);
  585. for (auto p : properties->Affinity) {
  586. this->ProcessorsAvailable.insert(p);
  587. }
  588. properties->Affinity.clear();
  589. runner.reset();
  590. if (started) {
  591. this->StartNextTests();
  592. }
  593. }
  594. void cmCTestMultiProcessHandler::UpdateCostData()
  595. {
  596. std::string fname = this->CTest->GetCostDataFile();
  597. std::string tmpout = fname + ".tmp";
  598. cmsys::ofstream fout;
  599. fout.open(tmpout.c_str());
  600. PropertiesMap temp = this->Properties;
  601. if (cmSystemTools::FileExists(fname)) {
  602. cmsys::ifstream fin;
  603. fin.open(fname.c_str());
  604. std::string line;
  605. while (std::getline(fin, line)) {
  606. if (line == "---") {
  607. break;
  608. }
  609. std::vector<std::string> parts = cmSystemTools::SplitString(line, ' ');
  610. // Format: <name> <previous_runs> <avg_cost>
  611. if (parts.size() < 3) {
  612. break;
  613. }
  614. std::string name = parts[0];
  615. int prev = atoi(parts[1].c_str());
  616. float cost = static_cast<float>(atof(parts[2].c_str()));
  617. int index = this->SearchByName(name);
  618. if (index == -1) {
  619. // This test is not in memory. We just rewrite the entry
  620. fout << name << " " << prev << " " << cost << "\n";
  621. } else {
  622. // Update with our new average cost
  623. fout << name << " " << this->Properties[index]->PreviousRuns << " "
  624. << this->Properties[index]->Cost << "\n";
  625. temp.erase(index);
  626. }
  627. }
  628. fin.close();
  629. cmSystemTools::RemoveFile(fname);
  630. }
  631. // Add all tests not previously listed in the file
  632. for (auto const& i : temp) {
  633. fout << i.second->Name << " " << i.second->PreviousRuns << " "
  634. << i.second->Cost << "\n";
  635. }
  636. // Write list of failed tests
  637. fout << "---\n";
  638. for (std::string const& f : *this->Failed) {
  639. fout << f << "\n";
  640. }
  641. fout.close();
  642. cmSystemTools::RenameFile(tmpout, fname);
  643. }
  644. void cmCTestMultiProcessHandler::ReadCostData()
  645. {
  646. std::string fname = this->CTest->GetCostDataFile();
  647. if (cmSystemTools::FileExists(fname, true)) {
  648. cmsys::ifstream fin;
  649. fin.open(fname.c_str());
  650. std::string line;
  651. while (std::getline(fin, line)) {
  652. if (line == "---") {
  653. break;
  654. }
  655. std::vector<std::string> parts = cmSystemTools::SplitString(line, ' ');
  656. // Probably an older version of the file, will be fixed next run
  657. if (parts.size() < 3) {
  658. fin.close();
  659. return;
  660. }
  661. std::string name = parts[0];
  662. int prev = atoi(parts[1].c_str());
  663. float cost = static_cast<float>(atof(parts[2].c_str()));
  664. int index = this->SearchByName(name);
  665. if (index == -1) {
  666. continue;
  667. }
  668. this->Properties[index]->PreviousRuns = prev;
  669. // When not running in parallel mode, don't use cost data
  670. if (this->ParallelLevel > 1 && this->Properties[index] &&
  671. this->Properties[index]->Cost == 0) {
  672. this->Properties[index]->Cost = cost;
  673. }
  674. }
  675. // Next part of the file is the failed tests
  676. while (std::getline(fin, line)) {
  677. if (!line.empty()) {
  678. this->LastTestsFailed.push_back(line);
  679. }
  680. }
  681. fin.close();
  682. }
  683. }
  684. int cmCTestMultiProcessHandler::SearchByName(std::string const& name)
  685. {
  686. int index = -1;
  687. for (auto const& p : this->Properties) {
  688. if (p.second->Name == name) {
  689. index = p.first;
  690. }
  691. }
  692. return index;
  693. }
  694. void cmCTestMultiProcessHandler::CreateTestCostList()
  695. {
  696. if (this->ParallelLevel > 1) {
  697. this->CreateParallelTestCostList();
  698. } else {
  699. this->CreateSerialTestCostList();
  700. }
  701. }
  702. void cmCTestMultiProcessHandler::CreateParallelTestCostList()
  703. {
  704. TestSet alreadyOrderedTests;
  705. std::list<TestSet> priorityStack;
  706. priorityStack.emplace_back();
  707. TestSet& topLevel = priorityStack.back();
  708. // In parallel test runs add previously failed tests to the front
  709. // of the cost list and queue other tests for further sorting
  710. for (auto const& t : this->PendingTests) {
  711. if (cm::contains(this->LastTestsFailed, this->Properties[t.first]->Name)) {
  712. // If the test failed last time, it should be run first.
  713. this->OrderedTests.push_back(t.first);
  714. alreadyOrderedTests.insert(t.first);
  715. } else {
  716. topLevel.insert(t.first);
  717. }
  718. }
  719. // In parallel test runs repeatedly move dependencies of the tests on
  720. // the current dependency level to the next level until no
  721. // further dependencies exist.
  722. while (!priorityStack.back().empty()) {
  723. TestSet& previousSet = priorityStack.back();
  724. priorityStack.emplace_back();
  725. TestSet& currentSet = priorityStack.back();
  726. for (auto const& i : previousSet) {
  727. TestSet const& dependencies = this->PendingTests[i].Depends;
  728. currentSet.insert(dependencies.begin(), dependencies.end());
  729. }
  730. for (auto const& i : currentSet) {
  731. previousSet.erase(i);
  732. }
  733. }
  734. // Remove the empty dependency level
  735. priorityStack.pop_back();
  736. // Reverse iterate over the different dependency levels (deepest first).
  737. // Sort tests within each level by COST and append them to the cost list.
  738. for (TestSet const& currentSet : cmReverseRange(priorityStack)) {
  739. TestList sortedCopy;
  740. cm::append(sortedCopy, currentSet);
  741. std::stable_sort(sortedCopy.begin(), sortedCopy.end(),
  742. TestComparator(this));
  743. for (auto const& j : sortedCopy) {
  744. if (!cm::contains(alreadyOrderedTests, j)) {
  745. this->OrderedTests.push_back(j);
  746. alreadyOrderedTests.insert(j);
  747. }
  748. }
  749. }
  750. }
  751. void cmCTestMultiProcessHandler::GetAllTestDependencies(int test,
  752. TestList& dependencies)
  753. {
  754. TestSet const& dependencySet = this->PendingTests[test].Depends;
  755. for (int i : dependencySet) {
  756. this->GetAllTestDependencies(i, dependencies);
  757. dependencies.push_back(i);
  758. }
  759. }
  760. void cmCTestMultiProcessHandler::CreateSerialTestCostList()
  761. {
  762. TestList presortedList;
  763. for (auto const& i : this->PendingTests) {
  764. presortedList.push_back(i.first);
  765. }
  766. std::stable_sort(presortedList.begin(), presortedList.end(),
  767. TestComparator(this));
  768. TestSet alreadyOrderedTests;
  769. for (int test : presortedList) {
  770. if (cm::contains(alreadyOrderedTests, test)) {
  771. continue;
  772. }
  773. TestList dependencies;
  774. this->GetAllTestDependencies(test, dependencies);
  775. for (int testDependency : dependencies) {
  776. if (!cm::contains(alreadyOrderedTests, testDependency)) {
  777. alreadyOrderedTests.insert(testDependency);
  778. this->OrderedTests.push_back(testDependency);
  779. }
  780. }
  781. alreadyOrderedTests.insert(test);
  782. this->OrderedTests.push_back(test);
  783. }
  784. }
  785. void cmCTestMultiProcessHandler::WriteCheckpoint(int index)
  786. {
  787. std::string fname =
  788. this->CTest->GetBinaryDir() + "/Testing/Temporary/CTestCheckpoint.txt";
  789. cmsys::ofstream fout;
  790. fout.open(fname.c_str(), std::ios::app);
  791. fout << index << "\n";
  792. fout.close();
  793. }
  794. void cmCTestMultiProcessHandler::MarkFinished()
  795. {
  796. std::string fname =
  797. this->CTest->GetBinaryDir() + "/Testing/Temporary/CTestCheckpoint.txt";
  798. cmSystemTools::RemoveFile(fname);
  799. }
  800. static Json::Value DumpToJsonArray(const std::set<std::string>& values)
  801. {
  802. Json::Value jsonArray = Json::arrayValue;
  803. for (const auto& it : values) {
  804. jsonArray.append(it);
  805. }
  806. return jsonArray;
  807. }
  808. static Json::Value DumpToJsonArray(const std::vector<std::string>& values)
  809. {
  810. Json::Value jsonArray = Json::arrayValue;
  811. for (const auto& it : values) {
  812. jsonArray.append(it);
  813. }
  814. return jsonArray;
  815. }
  816. static Json::Value DumpRegExToJsonArray(
  817. const std::vector<std::pair<cmsys::RegularExpression, std::string>>& values)
  818. {
  819. Json::Value jsonArray = Json::arrayValue;
  820. for (const auto& it : values) {
  821. jsonArray.append(it.second);
  822. }
  823. return jsonArray;
  824. }
  825. static Json::Value DumpMeasurementToJsonArray(
  826. const std::map<std::string, std::string>& values)
  827. {
  828. Json::Value jsonArray = Json::arrayValue;
  829. for (const auto& it : values) {
  830. Json::Value measurement = Json::objectValue;
  831. measurement["measurement"] = it.first;
  832. measurement["value"] = it.second;
  833. jsonArray.append(measurement);
  834. }
  835. return jsonArray;
  836. }
  837. static Json::Value DumpTimeoutAfterMatch(
  838. cmCTestTestHandler::cmCTestTestProperties& testProperties)
  839. {
  840. Json::Value timeoutAfterMatch = Json::objectValue;
  841. timeoutAfterMatch["timeout"] = testProperties.AlternateTimeout.count();
  842. timeoutAfterMatch["regex"] =
  843. DumpRegExToJsonArray(testProperties.TimeoutRegularExpressions);
  844. return timeoutAfterMatch;
  845. }
  846. static Json::Value DumpResourceGroupsToJsonArray(
  847. const std::vector<
  848. std::vector<cmCTestTestHandler::cmCTestTestResourceRequirement>>&
  849. resourceGroups)
  850. {
  851. Json::Value jsonResourceGroups = Json::arrayValue;
  852. for (auto const& it : resourceGroups) {
  853. Json::Value jsonResourceGroup = Json::objectValue;
  854. Json::Value requirements = Json::arrayValue;
  855. for (auto const& it2 : it) {
  856. Json::Value res = Json::objectValue;
  857. res[".type"] = it2.ResourceType;
  858. // res[".units"] = it2.UnitsNeeded; // Intentionally commented out
  859. res["slots"] = it2.SlotsNeeded;
  860. requirements.append(res);
  861. }
  862. jsonResourceGroup["requirements"] = requirements;
  863. jsonResourceGroups.append(jsonResourceGroup);
  864. }
  865. return jsonResourceGroups;
  866. }
  867. static Json::Value DumpCTestProperty(std::string const& name,
  868. Json::Value value)
  869. {
  870. Json::Value property = Json::objectValue;
  871. property["name"] = name;
  872. property["value"] = std::move(value);
  873. return property;
  874. }
  875. static Json::Value DumpCTestProperties(
  876. cmCTestTestHandler::cmCTestTestProperties& testProperties)
  877. {
  878. Json::Value properties = Json::arrayValue;
  879. if (!testProperties.AttachOnFail.empty()) {
  880. properties.append(DumpCTestProperty(
  881. "ATTACHED_FILES_ON_FAIL", DumpToJsonArray(testProperties.AttachOnFail)));
  882. }
  883. if (!testProperties.AttachedFiles.empty()) {
  884. properties.append(DumpCTestProperty(
  885. "ATTACHED_FILES", DumpToJsonArray(testProperties.AttachedFiles)));
  886. }
  887. if (testProperties.Cost != 0.0f) {
  888. properties.append(
  889. DumpCTestProperty("COST", static_cast<double>(testProperties.Cost)));
  890. }
  891. if (!testProperties.Depends.empty()) {
  892. properties.append(
  893. DumpCTestProperty("DEPENDS", DumpToJsonArray(testProperties.Depends)));
  894. }
  895. if (testProperties.Disabled) {
  896. properties.append(DumpCTestProperty("DISABLED", testProperties.Disabled));
  897. }
  898. if (!testProperties.Environment.empty()) {
  899. properties.append(DumpCTestProperty(
  900. "ENVIRONMENT", DumpToJsonArray(testProperties.Environment)));
  901. }
  902. if (!testProperties.EnvironmentModification.empty()) {
  903. properties.append(DumpCTestProperty(
  904. "ENVIRONMENT_MODIFICATION",
  905. DumpToJsonArray(testProperties.EnvironmentModification)));
  906. }
  907. if (!testProperties.ErrorRegularExpressions.empty()) {
  908. properties.append(DumpCTestProperty(
  909. "FAIL_REGULAR_EXPRESSION",
  910. DumpRegExToJsonArray(testProperties.ErrorRegularExpressions)));
  911. }
  912. if (!testProperties.SkipRegularExpressions.empty()) {
  913. properties.append(DumpCTestProperty(
  914. "SKIP_REGULAR_EXPRESSION",
  915. DumpRegExToJsonArray(testProperties.SkipRegularExpressions)));
  916. }
  917. if (!testProperties.FixturesCleanup.empty()) {
  918. properties.append(DumpCTestProperty(
  919. "FIXTURES_CLEANUP", DumpToJsonArray(testProperties.FixturesCleanup)));
  920. }
  921. if (!testProperties.FixturesRequired.empty()) {
  922. properties.append(DumpCTestProperty(
  923. "FIXTURES_REQUIRED", DumpToJsonArray(testProperties.FixturesRequired)));
  924. }
  925. if (!testProperties.FixturesSetup.empty()) {
  926. properties.append(DumpCTestProperty(
  927. "FIXTURES_SETUP", DumpToJsonArray(testProperties.FixturesSetup)));
  928. }
  929. if (!testProperties.Labels.empty()) {
  930. properties.append(
  931. DumpCTestProperty("LABELS", DumpToJsonArray(testProperties.Labels)));
  932. }
  933. if (!testProperties.Measurements.empty()) {
  934. properties.append(DumpCTestProperty(
  935. "MEASUREMENT", DumpMeasurementToJsonArray(testProperties.Measurements)));
  936. }
  937. if (!testProperties.RequiredRegularExpressions.empty()) {
  938. properties.append(DumpCTestProperty(
  939. "PASS_REGULAR_EXPRESSION",
  940. DumpRegExToJsonArray(testProperties.RequiredRegularExpressions)));
  941. }
  942. if (!testProperties.ResourceGroups.empty()) {
  943. properties.append(DumpCTestProperty(
  944. "RESOURCE_GROUPS",
  945. DumpResourceGroupsToJsonArray(testProperties.ResourceGroups)));
  946. }
  947. if (testProperties.WantAffinity) {
  948. properties.append(
  949. DumpCTestProperty("PROCESSOR_AFFINITY", testProperties.WantAffinity));
  950. }
  951. if (testProperties.Processors != 1) {
  952. properties.append(
  953. DumpCTestProperty("PROCESSORS", testProperties.Processors));
  954. }
  955. if (!testProperties.RequiredFiles.empty()) {
  956. properties.append(DumpCTestProperty(
  957. "REQUIRED_FILES", DumpToJsonArray(testProperties.RequiredFiles)));
  958. }
  959. if (!testProperties.LockedResources.empty()) {
  960. properties.append(DumpCTestProperty(
  961. "RESOURCE_LOCK", DumpToJsonArray(testProperties.LockedResources)));
  962. }
  963. if (testProperties.RunSerial) {
  964. properties.append(
  965. DumpCTestProperty("RUN_SERIAL", testProperties.RunSerial));
  966. }
  967. if (testProperties.SkipReturnCode != -1) {
  968. properties.append(
  969. DumpCTestProperty("SKIP_RETURN_CODE", testProperties.SkipReturnCode));
  970. }
  971. if (testProperties.Timeout) {
  972. properties.append(
  973. DumpCTestProperty("TIMEOUT", testProperties.Timeout->count()));
  974. }
  975. if (!testProperties.TimeoutRegularExpressions.empty()) {
  976. properties.append(DumpCTestProperty(
  977. "TIMEOUT_AFTER_MATCH", DumpTimeoutAfterMatch(testProperties)));
  978. }
  979. if (testProperties.WillFail) {
  980. properties.append(DumpCTestProperty("WILL_FAIL", testProperties.WillFail));
  981. }
  982. if (!testProperties.Directory.empty()) {
  983. properties.append(
  984. DumpCTestProperty("WORKING_DIRECTORY", testProperties.Directory));
  985. }
  986. return properties;
  987. }
  988. class BacktraceData
  989. {
  990. std::unordered_map<std::string, Json::ArrayIndex> CommandMap;
  991. std::unordered_map<std::string, Json::ArrayIndex> FileMap;
  992. std::unordered_map<cmListFileContext const*, Json::ArrayIndex> NodeMap;
  993. Json::Value Commands = Json::arrayValue;
  994. Json::Value Files = Json::arrayValue;
  995. Json::Value Nodes = Json::arrayValue;
  996. Json::ArrayIndex AddCommand(std::string const& command)
  997. {
  998. auto i = this->CommandMap.find(command);
  999. if (i == this->CommandMap.end()) {
  1000. i = this->CommandMap.emplace(command, this->Commands.size()).first;
  1001. this->Commands.append(command);
  1002. }
  1003. return i->second;
  1004. }
  1005. Json::ArrayIndex AddFile(std::string const& file)
  1006. {
  1007. auto i = this->FileMap.find(file);
  1008. if (i == this->FileMap.end()) {
  1009. i = this->FileMap.emplace(file, this->Files.size()).first;
  1010. this->Files.append(file);
  1011. }
  1012. return i->second;
  1013. }
  1014. public:
  1015. bool Add(cmListFileBacktrace const& bt, Json::ArrayIndex& index);
  1016. Json::Value Dump();
  1017. };
  1018. bool BacktraceData::Add(cmListFileBacktrace const& bt, Json::ArrayIndex& index)
  1019. {
  1020. if (bt.Empty()) {
  1021. return false;
  1022. }
  1023. cmListFileContext const* top = &bt.Top();
  1024. auto found = this->NodeMap.find(top);
  1025. if (found != this->NodeMap.end()) {
  1026. index = found->second;
  1027. return true;
  1028. }
  1029. Json::Value entry = Json::objectValue;
  1030. entry["file"] = this->AddFile(top->FilePath);
  1031. if (top->Line) {
  1032. entry["line"] = static_cast<int>(top->Line);
  1033. }
  1034. if (!top->Name.empty()) {
  1035. entry["command"] = this->AddCommand(top->Name);
  1036. }
  1037. Json::ArrayIndex parent;
  1038. if (this->Add(bt.Pop(), parent)) {
  1039. entry["parent"] = parent;
  1040. }
  1041. index = this->NodeMap[top] = this->Nodes.size();
  1042. this->Nodes.append(std::move(entry)); // NOLINT(*)
  1043. return true;
  1044. }
  1045. Json::Value BacktraceData::Dump()
  1046. {
  1047. Json::Value backtraceGraph;
  1048. this->CommandMap.clear();
  1049. this->FileMap.clear();
  1050. this->NodeMap.clear();
  1051. backtraceGraph["commands"] = std::move(this->Commands);
  1052. backtraceGraph["files"] = std::move(this->Files);
  1053. backtraceGraph["nodes"] = std::move(this->Nodes);
  1054. return backtraceGraph;
  1055. }
  1056. static void AddBacktrace(BacktraceData& backtraceGraph, Json::Value& object,
  1057. cmListFileBacktrace const& bt)
  1058. {
  1059. Json::ArrayIndex backtrace;
  1060. if (backtraceGraph.Add(bt, backtrace)) {
  1061. object["backtrace"] = backtrace;
  1062. }
  1063. }
  1064. static Json::Value DumpCTestInfo(
  1065. cmCTestRunTest& testRun,
  1066. cmCTestTestHandler::cmCTestTestProperties& testProperties,
  1067. BacktraceData& backtraceGraph)
  1068. {
  1069. Json::Value testInfo = Json::objectValue;
  1070. // test name should always be present
  1071. testInfo["name"] = testProperties.Name;
  1072. std::string const& config = testRun.GetCTest()->GetConfigType();
  1073. if (!config.empty()) {
  1074. testInfo["config"] = config;
  1075. }
  1076. std::string const& command = testRun.GetActualCommand();
  1077. if (!command.empty()) {
  1078. std::vector<std::string> commandAndArgs;
  1079. commandAndArgs.push_back(command);
  1080. const std::vector<std::string>& args = testRun.GetArguments();
  1081. if (!args.empty()) {
  1082. commandAndArgs.reserve(args.size() + 1);
  1083. cm::append(commandAndArgs, args);
  1084. }
  1085. testInfo["command"] = DumpToJsonArray(commandAndArgs);
  1086. }
  1087. Json::Value properties = DumpCTestProperties(testProperties);
  1088. if (!properties.empty()) {
  1089. testInfo["properties"] = properties;
  1090. }
  1091. if (!testProperties.Backtrace.Empty()) {
  1092. AddBacktrace(backtraceGraph, testInfo, testProperties.Backtrace);
  1093. }
  1094. return testInfo;
  1095. }
  1096. static Json::Value DumpVersion(int major, int minor)
  1097. {
  1098. Json::Value version = Json::objectValue;
  1099. version["major"] = major;
  1100. version["minor"] = minor;
  1101. return version;
  1102. }
  1103. void cmCTestMultiProcessHandler::PrintOutputAsJson()
  1104. {
  1105. this->TestHandler->SetMaxIndex(this->FindMaxIndex());
  1106. Json::Value result = Json::objectValue;
  1107. result["kind"] = "ctestInfo";
  1108. result["version"] = DumpVersion(1, 0);
  1109. BacktraceData backtraceGraph;
  1110. Json::Value tests = Json::arrayValue;
  1111. for (auto& it : this->Properties) {
  1112. cmCTestTestHandler::cmCTestTestProperties& p = *it.second;
  1113. // Don't worry if this fails, we are only showing the test list, not
  1114. // running the tests
  1115. cmWorkingDirectory workdir(p.Directory);
  1116. cmCTestRunTest testRun(*this, p.Index);
  1117. testRun.ComputeArguments();
  1118. // Skip tests not available in this configuration.
  1119. if (p.Args.size() >= 2 && p.Args[1] == "NOT_AVAILABLE") {
  1120. continue;
  1121. }
  1122. Json::Value testInfo = DumpCTestInfo(testRun, p, backtraceGraph);
  1123. tests.append(testInfo);
  1124. }
  1125. result["backtraceGraph"] = backtraceGraph.Dump();
  1126. result["tests"] = std::move(tests);
  1127. Json::StreamWriterBuilder builder;
  1128. builder["indentation"] = " ";
  1129. std::unique_ptr<Json::StreamWriter> jout(builder.newStreamWriter());
  1130. jout->write(result, &std::cout);
  1131. }
  1132. // For ShowOnly mode
  1133. void cmCTestMultiProcessHandler::PrintTestList()
  1134. {
  1135. if (this->CTest->GetOutputAsJson()) {
  1136. this->PrintOutputAsJson();
  1137. return;
  1138. }
  1139. this->TestHandler->SetMaxIndex(this->FindMaxIndex());
  1140. for (auto& it : this->Properties) {
  1141. cmCTestTestHandler::cmCTestTestProperties& p = *it.second;
  1142. // Don't worry if this fails, we are only showing the test list, not
  1143. // running the tests
  1144. cmWorkingDirectory workdir(p.Directory);
  1145. cmCTestRunTest testRun(*this, p.Index);
  1146. testRun.ComputeArguments(); // logs the command in verbose mode
  1147. if (!p.Labels.empty()) // print the labels
  1148. {
  1149. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1150. "Labels:", this->Quiet);
  1151. }
  1152. for (std::string const& label : p.Labels) {
  1153. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, " " << label,
  1154. this->Quiet);
  1155. }
  1156. if (!p.Labels.empty()) // print the labels
  1157. {
  1158. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, std::endl,
  1159. this->Quiet);
  1160. }
  1161. if (this->TestHandler->MemCheck) {
  1162. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, " Memory Check",
  1163. this->Quiet);
  1164. } else {
  1165. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, " Test", this->Quiet);
  1166. }
  1167. std::ostringstream indexStr;
  1168. indexStr << " #" << p.Index << ":";
  1169. cmCTestOptionalLog(
  1170. this->CTest, HANDLER_OUTPUT,
  1171. std::setw(3 + getNumWidth(this->TestHandler->GetMaxIndex()))
  1172. << indexStr.str(),
  1173. this->Quiet);
  1174. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, " " << p.Name,
  1175. this->Quiet);
  1176. if (p.Disabled) {
  1177. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, " (Disabled)",
  1178. this->Quiet);
  1179. }
  1180. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, std::endl, this->Quiet);
  1181. }
  1182. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  1183. std::endl
  1184. << "Total Tests: " << this->Total << std::endl,
  1185. this->Quiet);
  1186. }
  1187. void cmCTestMultiProcessHandler::PrintLabels()
  1188. {
  1189. std::set<std::string> allLabels;
  1190. for (auto& it : this->Properties) {
  1191. cmCTestTestHandler::cmCTestTestProperties& p = *it.second;
  1192. allLabels.insert(p.Labels.begin(), p.Labels.end());
  1193. }
  1194. if (!allLabels.empty()) {
  1195. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, "All Labels:" << std::endl,
  1196. this->Quiet);
  1197. } else {
  1198. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  1199. "No Labels Exist" << std::endl, this->Quiet);
  1200. }
  1201. for (std::string const& label : allLabels) {
  1202. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, " " << label << std::endl,
  1203. this->Quiet);
  1204. }
  1205. }
  1206. void cmCTestMultiProcessHandler::CheckResume()
  1207. {
  1208. std::string fname =
  1209. this->CTest->GetBinaryDir() + "/Testing/Temporary/CTestCheckpoint.txt";
  1210. if (this->CTest->GetFailover()) {
  1211. if (cmSystemTools::FileExists(fname, true)) {
  1212. *this->TestHandler->LogFile
  1213. << "Resuming previously interrupted test set" << std::endl
  1214. << "----------------------------------------------------------"
  1215. << std::endl;
  1216. cmsys::ifstream fin;
  1217. fin.open(fname.c_str());
  1218. std::string line;
  1219. while (std::getline(fin, line)) {
  1220. int index = atoi(line.c_str());
  1221. this->RemoveTest(index);
  1222. }
  1223. fin.close();
  1224. }
  1225. } else if (cmSystemTools::FileExists(fname, true)) {
  1226. cmSystemTools::RemoveFile(fname);
  1227. }
  1228. }
  1229. void cmCTestMultiProcessHandler::RemoveTest(int index)
  1230. {
  1231. this->ErasePendingTest(index);
  1232. this->Properties.erase(index);
  1233. this->Completed++;
  1234. }
  1235. int cmCTestMultiProcessHandler::FindMaxIndex()
  1236. {
  1237. int max = 0;
  1238. for (auto const& i : this->PendingTests) {
  1239. if (i.first > max) {
  1240. max = i.first;
  1241. }
  1242. }
  1243. return max;
  1244. }
  1245. // Returns true if no cycles exist in the dependency graph
  1246. bool cmCTestMultiProcessHandler::CheckCycles()
  1247. {
  1248. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1249. "Checking test dependency graph..." << std::endl,
  1250. this->Quiet);
  1251. for (auto const& it : this->PendingTests) {
  1252. // DFS from each element to itself
  1253. int root = it.first;
  1254. std::set<int> visited;
  1255. std::stack<int> s;
  1256. s.push(root);
  1257. while (!s.empty()) {
  1258. int test = s.top();
  1259. s.pop();
  1260. if (visited.insert(test).second) {
  1261. for (auto const& d : this->PendingTests[test].Depends) {
  1262. if (d == root) {
  1263. // cycle exists
  1264. cmCTestLog(
  1265. this->CTest, ERROR_MESSAGE,
  1266. "Error: a cycle exists in the test dependency graph "
  1267. "for the test \""
  1268. << this->Properties[root]->Name
  1269. << "\".\nPlease fix the cycle and run ctest again.\n");
  1270. return false;
  1271. }
  1272. s.push(d);
  1273. }
  1274. }
  1275. }
  1276. }
  1277. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1278. "Checking test dependency graph end" << std::endl,
  1279. this->Quiet);
  1280. return true;
  1281. }
  1282. bool cmCTestMultiProcessHandler::CheckGeneratedResourceSpec()
  1283. {
  1284. for (auto& test : this->Properties) {
  1285. if (!test.second->GeneratedResourceSpecFile.empty()) {
  1286. if (this->ResourceSpecSetupTest) {
  1287. cmCTestLog(
  1288. this->CTest, ERROR_MESSAGE,
  1289. "Only one test may define the GENERATED_RESOURCE_SPEC_FILE property"
  1290. << std::endl);
  1291. return false;
  1292. }
  1293. if (test.second->FixturesSetup.size() != 1) {
  1294. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1295. "Test that defines GENERATED_RESOURCE_SPEC_FILE must have "
  1296. "exactly one FIXTURES_SETUP"
  1297. << std::endl);
  1298. return false;
  1299. }
  1300. if (!cmSystemTools::FileIsFullPath(
  1301. test.second->GeneratedResourceSpecFile)) {
  1302. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1303. "GENERATED_RESOURCE_SPEC_FILE must be an absolute path"
  1304. << std::endl);
  1305. return false;
  1306. }
  1307. this->ResourceSpecSetupTest = test.first;
  1308. this->ResourceSpecSetupFixture = *test.second->FixturesSetup.begin();
  1309. }
  1310. }
  1311. if (!this->ResourceSpecSetupFixture.empty()) {
  1312. for (auto& test : this->Properties) {
  1313. if (!test.second->ResourceGroups.empty() &&
  1314. !test.second->FixturesRequired.count(
  1315. this->ResourceSpecSetupFixture)) {
  1316. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1317. "All tests that have RESOURCE_GROUPS must include the "
  1318. "resource spec generator fixture in their FIXTURES_REQUIRED"
  1319. << std::endl);
  1320. return false;
  1321. }
  1322. }
  1323. }
  1324. if (!this->ResourceSpecFile.empty()) {
  1325. if (this->ResourceSpecSetupTest) {
  1326. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1327. "GENERATED_RESOURCE_SPEC_FILE test property cannot be used "
  1328. "in conjunction with ResourceSpecFile option"
  1329. << std::endl);
  1330. return false;
  1331. }
  1332. std::string error;
  1333. if (!this->InitResourceAllocator(error)) {
  1334. cmCTestLog(this->CTest, ERROR_MESSAGE, error << std::endl);
  1335. return false;
  1336. }
  1337. }
  1338. return true;
  1339. }
  1340. bool cmCTestMultiProcessHandler::InitResourceAllocator(std::string& error)
  1341. {
  1342. if (!this->ResourceSpec.ReadFromJSONFile(this->ResourceSpecFile)) {
  1343. error = cmStrCat("Could not read/parse resource spec file ",
  1344. this->ResourceSpecFile, ": ",
  1345. this->ResourceSpec.parseState.GetErrorMessage());
  1346. return false;
  1347. }
  1348. this->UseResourceSpec = true;
  1349. this->ResourceAllocator.InitializeFromResourceSpec(this->ResourceSpec);
  1350. return true;
  1351. }