cmCTestMultiProcessHandler.cxx 36 KB

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