cmCTestMultiProcessHandler.cxx 41 KB

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