cmCTestMultiProcessHandler.cxx 42 KB

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