cmCTestMultiProcessHandler.cxx 40 KB

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