cmCTestMultiProcessHandler.cxx 45 KB

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