cmCTestMultiProcessHandler.cxx 42 KB

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