cmCTestMultiProcessHandler.cxx 46 KB

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