cmCTestMultiProcessHandler.cxx 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225
  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. // Sorts tests in descending order of cost
  41. bool operator()(int index1, int index2) const
  42. {
  43. return Handler->Properties[index1]->Cost >
  44. Handler->Properties[index2]->Cost;
  45. }
  46. private:
  47. cmCTestMultiProcessHandler* Handler;
  48. };
  49. cmCTestMultiProcessHandler::cmCTestMultiProcessHandler()
  50. {
  51. this->ParallelLevel = 1;
  52. this->TestLoad = 0;
  53. this->FakeLoadForTesting = 0;
  54. this->Completed = 0;
  55. this->RunningCount = 0;
  56. this->ProcessorsAvailable = cmAffinity::GetProcessorsAvailable();
  57. this->HaveAffinity = this->ProcessorsAvailable.size();
  58. this->HasCycles = false;
  59. this->SerialTestRunning = false;
  60. }
  61. cmCTestMultiProcessHandler::~cmCTestMultiProcessHandler() = default;
  62. // Set the tests
  63. void cmCTestMultiProcessHandler::SetTests(TestMap& tests,
  64. PropertiesMap& properties)
  65. {
  66. this->Tests = tests;
  67. this->Properties = properties;
  68. this->Total = this->Tests.size();
  69. // set test run map to false for all
  70. for (auto const& t : this->Tests) {
  71. this->TestRunningMap[t.first] = false;
  72. this->TestFinishMap[t.first] = false;
  73. }
  74. if (!this->CTest->GetShowOnly()) {
  75. this->ReadCostData();
  76. this->HasCycles = !this->CheckCycles();
  77. if (this->HasCycles) {
  78. return;
  79. }
  80. this->CreateTestCostList();
  81. }
  82. }
  83. // Set the max number of tests that can be run at the same time.
  84. void cmCTestMultiProcessHandler::SetParallelLevel(size_t level)
  85. {
  86. this->ParallelLevel = level < 1 ? 1 : level;
  87. }
  88. void cmCTestMultiProcessHandler::SetTestLoad(unsigned long load)
  89. {
  90. this->TestLoad = load;
  91. std::string fake_load_value;
  92. if (cmSystemTools::GetEnv("__CTEST_FAKE_LOAD_AVERAGE_FOR_TESTING",
  93. fake_load_value)) {
  94. if (!cmSystemTools::StringToULong(fake_load_value.c_str(),
  95. &this->FakeLoadForTesting)) {
  96. cmSystemTools::Error("Failed to parse fake load value: ",
  97. fake_load_value.c_str());
  98. }
  99. }
  100. }
  101. void cmCTestMultiProcessHandler::RunTests()
  102. {
  103. this->CheckResume();
  104. if (this->HasCycles) {
  105. return;
  106. }
  107. #ifdef CMAKE_UV_SIGNAL_HACK
  108. cmUVSignalHackRAII hackRAII;
  109. #endif
  110. this->TestHandler->SetMaxIndex(this->FindMaxIndex());
  111. uv_loop_init(&this->Loop);
  112. this->StartNextTests();
  113. uv_run(&this->Loop, UV_RUN_DEFAULT);
  114. uv_loop_close(&this->Loop);
  115. this->MarkFinished();
  116. this->UpdateCostData();
  117. }
  118. bool cmCTestMultiProcessHandler::StartTestProcess(int test)
  119. {
  120. if (this->HaveAffinity && this->Properties[test]->WantAffinity) {
  121. size_t needProcessors = this->GetProcessorsUsed(test);
  122. if (needProcessors > this->ProcessorsAvailable.size()) {
  123. return false;
  124. }
  125. std::vector<size_t> affinity;
  126. affinity.reserve(needProcessors);
  127. for (size_t i = 0; i < needProcessors; ++i) {
  128. auto p = this->ProcessorsAvailable.begin();
  129. affinity.push_back(*p);
  130. this->ProcessorsAvailable.erase(p);
  131. }
  132. this->Properties[test]->Affinity = std::move(affinity);
  133. }
  134. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  135. "test " << test << "\n", this->Quiet);
  136. this->TestRunningMap[test] = true; // mark the test as running
  137. // now remove the test itself
  138. this->EraseTest(test);
  139. this->RunningCount += GetProcessorsUsed(test);
  140. cmCTestRunTest* testRun = new cmCTestRunTest(*this);
  141. if (this->CTest->GetRepeatUntilFail()) {
  142. testRun->SetRunUntilFailOn();
  143. testRun->SetNumberOfRuns(this->CTest->GetTestRepeat());
  144. }
  145. testRun->SetIndex(test);
  146. testRun->SetTestProperties(this->Properties[test]);
  147. // Find any failed dependencies for this test. We assume the more common
  148. // scenario has no failed tests, so make it the outer loop.
  149. for (std::string const& f : *this->Failed) {
  150. if (this->Properties[test]->RequireSuccessDepends.find(f) !=
  151. this->Properties[test]->RequireSuccessDepends.end()) {
  152. testRun->AddFailedDependency(f);
  153. }
  154. }
  155. // Always lock the resources we'll be using, even if we fail to set the
  156. // working directory because FinishTestProcess() will try to unlock them
  157. this->LockResources(test);
  158. cmWorkingDirectory workdir(this->Properties[test]->Directory);
  159. if (workdir.Failed()) {
  160. testRun->StartFailure("Failed to change working directory to " +
  161. this->Properties[test]->Directory + " : " +
  162. std::strerror(workdir.GetLastResult()));
  163. } else {
  164. if (testRun->StartTest(this->Completed, this->Total)) {
  165. return true;
  166. }
  167. }
  168. this->FinishTestProcess(testRun, false);
  169. return false;
  170. }
  171. bool cmCTestMultiProcessHandler::CheckStopTimePassed()
  172. {
  173. if (!this->StopTimePassed) {
  174. std::chrono::system_clock::time_point stop_time =
  175. this->CTest->GetStopTime();
  176. if (stop_time != std::chrono::system_clock::time_point() &&
  177. stop_time <= std::chrono::system_clock::now()) {
  178. this->SetStopTimePassed();
  179. }
  180. }
  181. return this->StopTimePassed;
  182. }
  183. void cmCTestMultiProcessHandler::SetStopTimePassed()
  184. {
  185. if (!this->StopTimePassed) {
  186. cmCTestLog(this->CTest, ERROR_MESSAGE,
  187. "The stop time has been passed. "
  188. "Stopping all tests."
  189. << std::endl);
  190. this->StopTimePassed = true;
  191. }
  192. }
  193. void cmCTestMultiProcessHandler::LockResources(int index)
  194. {
  195. this->LockedResources.insert(
  196. this->Properties[index]->LockedResources.begin(),
  197. this->Properties[index]->LockedResources.end());
  198. if (this->Properties[index]->RunSerial) {
  199. this->SerialTestRunning = true;
  200. }
  201. }
  202. void cmCTestMultiProcessHandler::UnlockResources(int index)
  203. {
  204. for (std::string const& i : this->Properties[index]->LockedResources) {
  205. this->LockedResources.erase(i);
  206. }
  207. if (this->Properties[index]->RunSerial) {
  208. this->SerialTestRunning = false;
  209. }
  210. }
  211. void cmCTestMultiProcessHandler::EraseTest(int test)
  212. {
  213. this->Tests.erase(test);
  214. this->SortedTests.erase(
  215. std::find(this->SortedTests.begin(), this->SortedTests.end(), test));
  216. }
  217. inline size_t cmCTestMultiProcessHandler::GetProcessorsUsed(int test)
  218. {
  219. size_t processors = static_cast<int>(this->Properties[test]->Processors);
  220. // If processors setting is set higher than the -j
  221. // setting, we default to using all of the process slots.
  222. if (processors > this->ParallelLevel) {
  223. processors = this->ParallelLevel;
  224. }
  225. // Cap tests that want affinity to the maximum affinity available.
  226. if (this->HaveAffinity && processors > this->HaveAffinity &&
  227. this->Properties[test]->WantAffinity) {
  228. processors = this->HaveAffinity;
  229. }
  230. return processors;
  231. }
  232. std::string cmCTestMultiProcessHandler::GetName(int test)
  233. {
  234. return this->Properties[test]->Name;
  235. }
  236. bool cmCTestMultiProcessHandler::StartTest(int test)
  237. {
  238. // Check for locked resources
  239. for (std::string const& i : this->Properties[test]->LockedResources) {
  240. if (this->LockedResources.find(i) != this->LockedResources.end()) {
  241. return false;
  242. }
  243. }
  244. // if there are no depends left then run this test
  245. if (this->Tests[test].empty()) {
  246. return this->StartTestProcess(test);
  247. }
  248. // This test was not able to start because it is waiting
  249. // on depends to run
  250. return false;
  251. }
  252. void cmCTestMultiProcessHandler::StartNextTests()
  253. {
  254. if (this->TestLoadRetryTimer.get() != nullptr) {
  255. // This timer may be waiting to call StartNextTests again.
  256. // Since we have been called it is no longer needed.
  257. uv_timer_stop(this->TestLoadRetryTimer);
  258. }
  259. if (this->Tests.empty()) {
  260. this->TestLoadRetryTimer.reset();
  261. return;
  262. }
  263. if (this->CheckStopTimePassed()) {
  264. return;
  265. }
  266. size_t numToStart = 0;
  267. if (this->RunningCount < this->ParallelLevel) {
  268. numToStart = this->ParallelLevel - this->RunningCount;
  269. }
  270. if (numToStart == 0) {
  271. return;
  272. }
  273. // Don't start any new tests if one with the RUN_SERIAL property
  274. // is already running.
  275. if (this->SerialTestRunning) {
  276. return;
  277. }
  278. bool allTestsFailedTestLoadCheck = false;
  279. size_t minProcessorsRequired = this->ParallelLevel;
  280. std::string testWithMinProcessors;
  281. cmsys::SystemInformation info;
  282. unsigned long systemLoad = 0;
  283. size_t spareLoad = 0;
  284. if (this->TestLoad > 0) {
  285. // Activate possible wait.
  286. allTestsFailedTestLoadCheck = true;
  287. // Check for a fake load average value used in testing.
  288. if (this->FakeLoadForTesting > 0) {
  289. systemLoad = this->FakeLoadForTesting;
  290. // Drop the fake load for the next iteration to a value low enough
  291. // that the next iteration will start tests.
  292. this->FakeLoadForTesting = 1;
  293. }
  294. // If it's not set, look up the true load average.
  295. else {
  296. systemLoad = static_cast<unsigned long>(ceil(info.GetLoadAverage()));
  297. }
  298. spareLoad =
  299. (this->TestLoad > systemLoad ? this->TestLoad - systemLoad : 0);
  300. // Don't start more tests than the spare load can support.
  301. if (numToStart > spareLoad) {
  302. numToStart = spareLoad;
  303. }
  304. }
  305. TestList copy = this->SortedTests;
  306. for (auto const& test : copy) {
  307. // Take a nap if we're currently performing a RUN_SERIAL test.
  308. if (this->SerialTestRunning) {
  309. break;
  310. }
  311. // We can only start a RUN_SERIAL test if no other tests are also running.
  312. if (this->Properties[test]->RunSerial && this->RunningCount > 0) {
  313. continue;
  314. }
  315. size_t processors = GetProcessorsUsed(test);
  316. bool testLoadOk = true;
  317. if (this->TestLoad > 0) {
  318. if (processors <= spareLoad) {
  319. cmCTestLog(this->CTest, DEBUG,
  320. "OK to run " << GetName(test) << ", it requires "
  321. << processors << " procs & system load is: "
  322. << systemLoad << std::endl);
  323. allTestsFailedTestLoadCheck = false;
  324. } else {
  325. testLoadOk = false;
  326. }
  327. }
  328. if (processors <= minProcessorsRequired) {
  329. minProcessorsRequired = processors;
  330. testWithMinProcessors = GetName(test);
  331. }
  332. if (testLoadOk && processors <= numToStart && this->StartTest(test)) {
  333. numToStart -= processors;
  334. } else if (numToStart == 0) {
  335. break;
  336. }
  337. }
  338. if (allTestsFailedTestLoadCheck) {
  339. // Find out whether there are any non RUN_SERIAL tests left, so that the
  340. // correct warning may be displayed.
  341. bool onlyRunSerialTestsLeft = true;
  342. for (auto const& test : copy) {
  343. if (!this->Properties[test]->RunSerial) {
  344. onlyRunSerialTestsLeft = false;
  345. }
  346. }
  347. cmCTestLog(this->CTest, HANDLER_OUTPUT, "***** WAITING, ");
  348. if (this->SerialTestRunning) {
  349. cmCTestLog(this->CTest, HANDLER_OUTPUT,
  350. "Waiting for RUN_SERIAL test to finish.");
  351. } else if (onlyRunSerialTestsLeft) {
  352. cmCTestLog(this->CTest, HANDLER_OUTPUT,
  353. "Only RUN_SERIAL tests remain, awaiting available slot.");
  354. } else {
  355. /* clang-format off */
  356. cmCTestLog(this->CTest, HANDLER_OUTPUT,
  357. "System Load: " << systemLoad << ", "
  358. "Max Allowed Load: " << this->TestLoad << ", "
  359. "Smallest test " << testWithMinProcessors <<
  360. " requires " << minProcessorsRequired);
  361. /* clang-format on */
  362. }
  363. cmCTestLog(this->CTest, HANDLER_OUTPUT, "*****" << std::endl);
  364. // Wait between 1 and 5 seconds before trying again.
  365. unsigned int milliseconds = (cmSystemTools::RandomSeed() % 5 + 1) * 1000;
  366. if (this->FakeLoadForTesting) {
  367. milliseconds = 10;
  368. }
  369. if (this->TestLoadRetryTimer.get() == nullptr) {
  370. this->TestLoadRetryTimer.init(this->Loop, this);
  371. }
  372. this->TestLoadRetryTimer.start(
  373. &cmCTestMultiProcessHandler::OnTestLoadRetryCB, milliseconds, 0);
  374. }
  375. }
  376. void cmCTestMultiProcessHandler::OnTestLoadRetryCB(uv_timer_t* timer)
  377. {
  378. auto self = static_cast<cmCTestMultiProcessHandler*>(timer->data);
  379. self->StartNextTests();
  380. }
  381. void cmCTestMultiProcessHandler::FinishTestProcess(cmCTestRunTest* runner,
  382. bool started)
  383. {
  384. this->Completed++;
  385. int test = runner->GetIndex();
  386. auto properties = runner->GetTestProperties();
  387. bool testResult = runner->EndTest(this->Completed, this->Total, started);
  388. if (runner->TimedOutForStopTime()) {
  389. this->SetStopTimePassed();
  390. }
  391. if (started) {
  392. if (!this->StopTimePassed && runner->StartAgain(this->Completed)) {
  393. this->Completed--; // remove the completed test because run again
  394. return;
  395. }
  396. }
  397. if (testResult) {
  398. this->Passed->push_back(properties->Name);
  399. } else if (!properties->Disabled) {
  400. this->Failed->push_back(properties->Name);
  401. }
  402. for (auto& t : this->Tests) {
  403. t.second.erase(test);
  404. }
  405. this->TestFinishMap[test] = true;
  406. this->TestRunningMap[test] = false;
  407. this->WriteCheckpoint(test);
  408. this->UnlockResources(test);
  409. this->RunningCount -= GetProcessorsUsed(test);
  410. for (auto p : properties->Affinity) {
  411. this->ProcessorsAvailable.insert(p);
  412. }
  413. properties->Affinity.clear();
  414. delete runner;
  415. if (started) {
  416. this->StartNextTests();
  417. }
  418. }
  419. void cmCTestMultiProcessHandler::UpdateCostData()
  420. {
  421. std::string fname = this->CTest->GetCostDataFile();
  422. std::string tmpout = fname + ".tmp";
  423. cmsys::ofstream fout;
  424. fout.open(tmpout.c_str());
  425. PropertiesMap temp = this->Properties;
  426. if (cmSystemTools::FileExists(fname)) {
  427. cmsys::ifstream fin;
  428. fin.open(fname.c_str());
  429. std::string line;
  430. while (std::getline(fin, line)) {
  431. if (line == "---") {
  432. break;
  433. }
  434. std::vector<std::string> parts = cmSystemTools::SplitString(line, ' ');
  435. // Format: <name> <previous_runs> <avg_cost>
  436. if (parts.size() < 3) {
  437. break;
  438. }
  439. std::string name = parts[0];
  440. int prev = atoi(parts[1].c_str());
  441. float cost = static_cast<float>(atof(parts[2].c_str()));
  442. int index = this->SearchByName(name);
  443. if (index == -1) {
  444. // This test is not in memory. We just rewrite the entry
  445. fout << name << " " << prev << " " << cost << "\n";
  446. } else {
  447. // Update with our new average cost
  448. fout << name << " " << this->Properties[index]->PreviousRuns << " "
  449. << this->Properties[index]->Cost << "\n";
  450. temp.erase(index);
  451. }
  452. }
  453. fin.close();
  454. cmSystemTools::RemoveFile(fname);
  455. }
  456. // Add all tests not previously listed in the file
  457. for (auto const& i : temp) {
  458. fout << i.second->Name << " " << i.second->PreviousRuns << " "
  459. << i.second->Cost << "\n";
  460. }
  461. // Write list of failed tests
  462. fout << "---\n";
  463. for (std::string const& f : *this->Failed) {
  464. fout << f << "\n";
  465. }
  466. fout.close();
  467. cmSystemTools::RenameFile(tmpout, fname);
  468. }
  469. void cmCTestMultiProcessHandler::ReadCostData()
  470. {
  471. std::string fname = this->CTest->GetCostDataFile();
  472. if (cmSystemTools::FileExists(fname, true)) {
  473. cmsys::ifstream fin;
  474. fin.open(fname.c_str());
  475. std::string line;
  476. while (std::getline(fin, line)) {
  477. if (line == "---") {
  478. break;
  479. }
  480. std::vector<std::string> parts = cmSystemTools::SplitString(line, ' ');
  481. // Probably an older version of the file, will be fixed next run
  482. if (parts.size() < 3) {
  483. fin.close();
  484. return;
  485. }
  486. std::string name = parts[0];
  487. int prev = atoi(parts[1].c_str());
  488. float cost = static_cast<float>(atof(parts[2].c_str()));
  489. int index = this->SearchByName(name);
  490. if (index == -1) {
  491. continue;
  492. }
  493. this->Properties[index]->PreviousRuns = prev;
  494. // When not running in parallel mode, don't use cost data
  495. if (this->ParallelLevel > 1 && this->Properties[index] &&
  496. this->Properties[index]->Cost == 0) {
  497. this->Properties[index]->Cost = cost;
  498. }
  499. }
  500. // Next part of the file is the failed tests
  501. while (std::getline(fin, line)) {
  502. if (!line.empty()) {
  503. this->LastTestsFailed.push_back(line);
  504. }
  505. }
  506. fin.close();
  507. }
  508. }
  509. int cmCTestMultiProcessHandler::SearchByName(std::string const& name)
  510. {
  511. int index = -1;
  512. for (auto const& p : this->Properties) {
  513. if (p.second->Name == name) {
  514. index = p.first;
  515. }
  516. }
  517. return index;
  518. }
  519. void cmCTestMultiProcessHandler::CreateTestCostList()
  520. {
  521. if (this->ParallelLevel > 1) {
  522. CreateParallelTestCostList();
  523. } else {
  524. CreateSerialTestCostList();
  525. }
  526. }
  527. void cmCTestMultiProcessHandler::CreateParallelTestCostList()
  528. {
  529. TestSet alreadySortedTests;
  530. std::list<TestSet> priorityStack;
  531. priorityStack.emplace_back();
  532. TestSet& topLevel = priorityStack.back();
  533. // In parallel test runs add previously failed tests to the front
  534. // of the cost list and queue other tests for further sorting
  535. for (auto const& t : this->Tests) {
  536. if (std::find(this->LastTestsFailed.begin(), this->LastTestsFailed.end(),
  537. this->Properties[t.first]->Name) !=
  538. this->LastTestsFailed.end()) {
  539. // If the test failed last time, it should be run first.
  540. this->SortedTests.push_back(t.first);
  541. alreadySortedTests.insert(t.first);
  542. } else {
  543. topLevel.insert(t.first);
  544. }
  545. }
  546. // In parallel test runs repeatedly move dependencies of the tests on
  547. // the current dependency level to the next level until no
  548. // further dependencies exist.
  549. while (!priorityStack.back().empty()) {
  550. TestSet& previousSet = priorityStack.back();
  551. priorityStack.emplace_back();
  552. TestSet& currentSet = priorityStack.back();
  553. for (auto const& i : previousSet) {
  554. TestSet const& dependencies = this->Tests[i];
  555. currentSet.insert(dependencies.begin(), dependencies.end());
  556. }
  557. for (auto const& i : currentSet) {
  558. previousSet.erase(i);
  559. }
  560. }
  561. // Remove the empty dependency level
  562. priorityStack.pop_back();
  563. // Reverse iterate over the different dependency levels (deepest first).
  564. // Sort tests within each level by COST and append them to the cost list.
  565. for (std::list<TestSet>::reverse_iterator i = priorityStack.rbegin();
  566. i != priorityStack.rend(); ++i) {
  567. TestSet const& currentSet = *i;
  568. TestComparator comp(this);
  569. TestList sortedCopy;
  570. sortedCopy.insert(sortedCopy.end(), currentSet.begin(), currentSet.end());
  571. std::stable_sort(sortedCopy.begin(), sortedCopy.end(), comp);
  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. TestComparator comp(this);
  596. std::stable_sort(presortedList.begin(), presortedList.end(), comp);
  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. commandAndArgs.insert(commandAndArgs.end(), args.begin(), args.end());
  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. }