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