cmCTestMultiProcessHandler.cxx 36 KB

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