cmCTestMultiProcessHandler.cxx 42 KB

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