cmCTestMultiProcessHandler.cxx 35 KB

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