cmCTestMultiProcessHandler.cxx 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385
  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->GetRerunMode() != cmCTest::Rerun::Never) {
  154. testRun->SetRerunMode(this->CTest->GetRerunMode());
  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]->Processes.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]->Processes) {
  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 DumpProcessesToJsonArray(
  794. const std::vector<
  795. std::vector<cmCTestTestHandler::cmCTestTestResourceRequirement>>&
  796. processes)
  797. {
  798. Json::Value jsonProcesses = Json::arrayValue;
  799. for (auto const& it : processes) {
  800. Json::Value jsonProcess = 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. jsonProcess["requirements"] = requirements;
  810. jsonProcesses.append(jsonProcess);
  811. }
  812. return jsonProcesses;
  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.Processes.empty()) {
  885. properties.append(DumpCTestProperty(
  886. "PROCESSES", DumpProcessesToJsonArray(testProperties.Processes)));
  887. }
  888. if (testProperties.WantAffinity) {
  889. properties.append(
  890. DumpCTestProperty("PROCESSOR_AFFINITY", testProperties.WantAffinity));
  891. }
  892. if (testProperties.Processors != 1) {
  893. properties.append(
  894. DumpCTestProperty("PROCESSORS", testProperties.Processors));
  895. }
  896. if (!testProperties.RequiredFiles.empty()) {
  897. properties.append(DumpCTestProperty(
  898. "REQUIRED_FILES", DumpToJsonArray(testProperties.RequiredFiles)));
  899. }
  900. if (!testProperties.LockedResources.empty()) {
  901. properties.append(DumpCTestProperty(
  902. "RESOURCE_LOCK", DumpToJsonArray(testProperties.LockedResources)));
  903. }
  904. if (testProperties.RunSerial) {
  905. properties.append(
  906. DumpCTestProperty("RUN_SERIAL", testProperties.RunSerial));
  907. }
  908. if (testProperties.SkipReturnCode != -1) {
  909. properties.append(
  910. DumpCTestProperty("SKIP_RETURN_CODE", testProperties.SkipReturnCode));
  911. }
  912. if (testProperties.ExplicitTimeout) {
  913. properties.append(
  914. DumpCTestProperty("TIMEOUT", testProperties.Timeout.count()));
  915. }
  916. if (!testProperties.TimeoutRegularExpressions.empty()) {
  917. properties.append(DumpCTestProperty(
  918. "TIMEOUT_AFTER_MATCH", DumpTimeoutAfterMatch(testProperties)));
  919. }
  920. if (testProperties.WillFail) {
  921. properties.append(DumpCTestProperty("WILL_FAIL", testProperties.WillFail));
  922. }
  923. if (!testProperties.Directory.empty()) {
  924. properties.append(
  925. DumpCTestProperty("WORKING_DIRECTORY", testProperties.Directory));
  926. }
  927. return properties;
  928. }
  929. class BacktraceData
  930. {
  931. std::unordered_map<std::string, Json::ArrayIndex> CommandMap;
  932. std::unordered_map<std::string, Json::ArrayIndex> FileMap;
  933. std::unordered_map<cmListFileContext const*, Json::ArrayIndex> NodeMap;
  934. Json::Value Commands = Json::arrayValue;
  935. Json::Value Files = Json::arrayValue;
  936. Json::Value Nodes = Json::arrayValue;
  937. Json::ArrayIndex AddCommand(std::string const& command)
  938. {
  939. auto i = this->CommandMap.find(command);
  940. if (i == this->CommandMap.end()) {
  941. i = this->CommandMap.emplace(command, this->Commands.size()).first;
  942. this->Commands.append(command);
  943. }
  944. return i->second;
  945. }
  946. Json::ArrayIndex AddFile(std::string const& file)
  947. {
  948. auto i = this->FileMap.find(file);
  949. if (i == this->FileMap.end()) {
  950. i = this->FileMap.emplace(file, this->Files.size()).first;
  951. this->Files.append(file);
  952. }
  953. return i->second;
  954. }
  955. public:
  956. bool Add(cmListFileBacktrace const& bt, Json::ArrayIndex& index);
  957. Json::Value Dump();
  958. };
  959. bool BacktraceData::Add(cmListFileBacktrace const& bt, Json::ArrayIndex& index)
  960. {
  961. if (bt.Empty()) {
  962. return false;
  963. }
  964. cmListFileContext const* top = &bt.Top();
  965. auto found = this->NodeMap.find(top);
  966. if (found != this->NodeMap.end()) {
  967. index = found->second;
  968. return true;
  969. }
  970. Json::Value entry = Json::objectValue;
  971. entry["file"] = this->AddFile(top->FilePath);
  972. if (top->Line) {
  973. entry["line"] = static_cast<int>(top->Line);
  974. }
  975. if (!top->Name.empty()) {
  976. entry["command"] = this->AddCommand(top->Name);
  977. }
  978. Json::ArrayIndex parent;
  979. if (this->Add(bt.Pop(), parent)) {
  980. entry["parent"] = parent;
  981. }
  982. index = this->NodeMap[top] = this->Nodes.size();
  983. this->Nodes.append(std::move(entry)); // NOLINT(*)
  984. return true;
  985. }
  986. Json::Value BacktraceData::Dump()
  987. {
  988. Json::Value backtraceGraph;
  989. this->CommandMap.clear();
  990. this->FileMap.clear();
  991. this->NodeMap.clear();
  992. backtraceGraph["commands"] = std::move(this->Commands);
  993. backtraceGraph["files"] = std::move(this->Files);
  994. backtraceGraph["nodes"] = std::move(this->Nodes);
  995. return backtraceGraph;
  996. }
  997. static void AddBacktrace(BacktraceData& backtraceGraph, Json::Value& object,
  998. cmListFileBacktrace const& bt)
  999. {
  1000. Json::ArrayIndex backtrace;
  1001. if (backtraceGraph.Add(bt, backtrace)) {
  1002. object["backtrace"] = backtrace;
  1003. }
  1004. }
  1005. static Json::Value DumpCTestInfo(
  1006. cmCTestRunTest& testRun,
  1007. cmCTestTestHandler::cmCTestTestProperties& testProperties,
  1008. BacktraceData& backtraceGraph)
  1009. {
  1010. Json::Value testInfo = Json::objectValue;
  1011. // test name should always be present
  1012. testInfo["name"] = testProperties.Name;
  1013. std::string const& config = testRun.GetCTest()->GetConfigType();
  1014. if (!config.empty()) {
  1015. testInfo["config"] = config;
  1016. }
  1017. std::string const& command = testRun.GetActualCommand();
  1018. if (!command.empty()) {
  1019. std::vector<std::string> commandAndArgs;
  1020. commandAndArgs.push_back(command);
  1021. const std::vector<std::string>& args = testRun.GetArguments();
  1022. if (!args.empty()) {
  1023. commandAndArgs.reserve(args.size() + 1);
  1024. cmAppend(commandAndArgs, args);
  1025. }
  1026. testInfo["command"] = DumpToJsonArray(commandAndArgs);
  1027. }
  1028. Json::Value properties = DumpCTestProperties(testProperties);
  1029. if (!properties.empty()) {
  1030. testInfo["properties"] = properties;
  1031. }
  1032. if (!testProperties.Backtrace.Empty()) {
  1033. AddBacktrace(backtraceGraph, testInfo, testProperties.Backtrace);
  1034. }
  1035. return testInfo;
  1036. }
  1037. static Json::Value DumpVersion(int major, int minor)
  1038. {
  1039. Json::Value version = Json::objectValue;
  1040. version["major"] = major;
  1041. version["minor"] = minor;
  1042. return version;
  1043. }
  1044. void cmCTestMultiProcessHandler::PrintOutputAsJson()
  1045. {
  1046. this->TestHandler->SetMaxIndex(this->FindMaxIndex());
  1047. Json::Value result = Json::objectValue;
  1048. result["kind"] = "ctestInfo";
  1049. result["version"] = DumpVersion(1, 0);
  1050. BacktraceData backtraceGraph;
  1051. Json::Value tests = Json::arrayValue;
  1052. for (auto& it : this->Properties) {
  1053. cmCTestTestHandler::cmCTestTestProperties& p = *it.second;
  1054. // Don't worry if this fails, we are only showing the test list, not
  1055. // running the tests
  1056. cmWorkingDirectory workdir(p.Directory);
  1057. cmCTestRunTest testRun(*this);
  1058. testRun.SetIndex(p.Index);
  1059. testRun.SetTestProperties(&p);
  1060. testRun.ComputeArguments();
  1061. // Skip tests not available in this configuration.
  1062. if (p.Args.size() >= 2 && p.Args[1] == "NOT_AVAILABLE") {
  1063. continue;
  1064. }
  1065. Json::Value testInfo = DumpCTestInfo(testRun, p, backtraceGraph);
  1066. tests.append(testInfo);
  1067. }
  1068. result["backtraceGraph"] = backtraceGraph.Dump();
  1069. result["tests"] = std::move(tests);
  1070. Json::StreamWriterBuilder builder;
  1071. builder["indentation"] = " ";
  1072. std::unique_ptr<Json::StreamWriter> jout(builder.newStreamWriter());
  1073. jout->write(result, &std::cout);
  1074. }
  1075. // For ShowOnly mode
  1076. void cmCTestMultiProcessHandler::PrintTestList()
  1077. {
  1078. if (this->CTest->GetOutputAsJson()) {
  1079. PrintOutputAsJson();
  1080. return;
  1081. }
  1082. this->TestHandler->SetMaxIndex(this->FindMaxIndex());
  1083. int count = 0;
  1084. for (auto& it : this->Properties) {
  1085. count++;
  1086. cmCTestTestHandler::cmCTestTestProperties& p = *it.second;
  1087. // Don't worry if this fails, we are only showing the test list, not
  1088. // running the tests
  1089. cmWorkingDirectory workdir(p.Directory);
  1090. cmCTestRunTest testRun(*this);
  1091. testRun.SetIndex(p.Index);
  1092. testRun.SetTestProperties(&p);
  1093. testRun.ComputeArguments(); // logs the command in verbose mode
  1094. if (!p.Labels.empty()) // print the labels
  1095. {
  1096. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1097. "Labels:", this->Quiet);
  1098. }
  1099. for (std::string const& label : p.Labels) {
  1100. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, " " << label,
  1101. this->Quiet);
  1102. }
  1103. if (!p.Labels.empty()) // print the labels
  1104. {
  1105. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, std::endl,
  1106. this->Quiet);
  1107. }
  1108. if (this->TestHandler->MemCheck) {
  1109. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, " Memory Check",
  1110. this->Quiet);
  1111. } else {
  1112. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, " Test", this->Quiet);
  1113. }
  1114. std::ostringstream indexStr;
  1115. indexStr << " #" << p.Index << ":";
  1116. cmCTestOptionalLog(
  1117. this->CTest, HANDLER_OUTPUT,
  1118. std::setw(3 + getNumWidth(this->TestHandler->GetMaxIndex()))
  1119. << indexStr.str(),
  1120. this->Quiet);
  1121. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, " " << p.Name,
  1122. this->Quiet);
  1123. if (p.Disabled) {
  1124. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, " (Disabled)",
  1125. this->Quiet);
  1126. }
  1127. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, std::endl, this->Quiet);
  1128. }
  1129. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  1130. std::endl
  1131. << "Total Tests: " << this->Total << std::endl,
  1132. this->Quiet);
  1133. }
  1134. void cmCTestMultiProcessHandler::PrintLabels()
  1135. {
  1136. std::set<std::string> allLabels;
  1137. for (auto& it : this->Properties) {
  1138. cmCTestTestHandler::cmCTestTestProperties& p = *it.second;
  1139. allLabels.insert(p.Labels.begin(), p.Labels.end());
  1140. }
  1141. if (!allLabels.empty()) {
  1142. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, "All Labels:" << std::endl,
  1143. this->Quiet);
  1144. } else {
  1145. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  1146. "No Labels Exist" << std::endl, this->Quiet);
  1147. }
  1148. for (std::string const& label : allLabels) {
  1149. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, " " << label << std::endl,
  1150. this->Quiet);
  1151. }
  1152. }
  1153. void cmCTestMultiProcessHandler::CheckResume()
  1154. {
  1155. std::string fname =
  1156. this->CTest->GetBinaryDir() + "/Testing/Temporary/CTestCheckpoint.txt";
  1157. if (this->CTest->GetFailover()) {
  1158. if (cmSystemTools::FileExists(fname, true)) {
  1159. *this->TestHandler->LogFile
  1160. << "Resuming previously interrupted test set" << std::endl
  1161. << "----------------------------------------------------------"
  1162. << std::endl;
  1163. cmsys::ifstream fin;
  1164. fin.open(fname.c_str());
  1165. std::string line;
  1166. while (std::getline(fin, line)) {
  1167. int index = atoi(line.c_str());
  1168. this->RemoveTest(index);
  1169. }
  1170. fin.close();
  1171. }
  1172. } else if (cmSystemTools::FileExists(fname, true)) {
  1173. cmSystemTools::RemoveFile(fname);
  1174. }
  1175. }
  1176. void cmCTestMultiProcessHandler::RemoveTest(int index)
  1177. {
  1178. this->EraseTest(index);
  1179. this->Properties.erase(index);
  1180. this->TestRunningMap[index] = false;
  1181. this->TestFinishMap[index] = true;
  1182. this->Completed++;
  1183. }
  1184. int cmCTestMultiProcessHandler::FindMaxIndex()
  1185. {
  1186. int max = 0;
  1187. for (auto const& i : this->Tests) {
  1188. if (i.first > max) {
  1189. max = i.first;
  1190. }
  1191. }
  1192. return max;
  1193. }
  1194. // Returns true if no cycles exist in the dependency graph
  1195. bool cmCTestMultiProcessHandler::CheckCycles()
  1196. {
  1197. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1198. "Checking test dependency graph..." << std::endl,
  1199. this->Quiet);
  1200. for (auto const& it : this->Tests) {
  1201. // DFS from each element to itself
  1202. int root = it.first;
  1203. std::set<int> visited;
  1204. std::stack<int> s;
  1205. s.push(root);
  1206. while (!s.empty()) {
  1207. int test = s.top();
  1208. s.pop();
  1209. if (visited.insert(test).second) {
  1210. for (auto const& d : this->Tests[test]) {
  1211. if (d == root) {
  1212. // cycle exists
  1213. cmCTestLog(
  1214. this->CTest, ERROR_MESSAGE,
  1215. "Error: a cycle exists in the test dependency graph "
  1216. "for the test \""
  1217. << this->Properties[root]->Name
  1218. << "\".\nPlease fix the cycle and run ctest again.\n");
  1219. return false;
  1220. }
  1221. s.push(d);
  1222. }
  1223. }
  1224. }
  1225. }
  1226. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1227. "Checking test dependency graph end" << std::endl,
  1228. this->Quiet);
  1229. return true;
  1230. }