cmCTestMultiProcessHandler.cxx 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892
  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 "cmSystemTools.h"
  9. #include "cmWorkingDirectory.h"
  10. #include "cm_uv.h"
  11. #include "cmUVSignalHackRAII.h" // IWYU pragma: keep
  12. #include "cmsys/FStream.hxx"
  13. #include "cmsys/SystemInformation.hxx"
  14. #include <algorithm>
  15. #include <chrono>
  16. #include <cstring>
  17. #include <iomanip>
  18. #include <list>
  19. #include <math.h>
  20. #include <sstream>
  21. #include <stack>
  22. #include <stdlib.h>
  23. #include <utility>
  24. class TestComparator
  25. {
  26. public:
  27. TestComparator(cmCTestMultiProcessHandler* handler)
  28. : Handler(handler)
  29. {
  30. }
  31. ~TestComparator() {}
  32. // Sorts tests in descending order of cost
  33. bool operator()(int index1, int index2) const
  34. {
  35. return Handler->Properties[index1]->Cost >
  36. Handler->Properties[index2]->Cost;
  37. }
  38. private:
  39. cmCTestMultiProcessHandler* Handler;
  40. };
  41. cmCTestMultiProcessHandler::cmCTestMultiProcessHandler()
  42. {
  43. this->ParallelLevel = 1;
  44. this->TestLoad = 0;
  45. this->FakeLoadForTesting = 0;
  46. this->Completed = 0;
  47. this->RunningCount = 0;
  48. this->ProcessorsAvailable = cmAffinity::GetProcessorsAvailable();
  49. this->HaveAffinity = this->ProcessorsAvailable.size();
  50. this->HasCycles = false;
  51. this->SerialTestRunning = false;
  52. }
  53. cmCTestMultiProcessHandler::~cmCTestMultiProcessHandler()
  54. {
  55. }
  56. // Set the tests
  57. void cmCTestMultiProcessHandler::SetTests(TestMap& tests,
  58. PropertiesMap& properties)
  59. {
  60. this->Tests = tests;
  61. this->Properties = properties;
  62. this->Total = this->Tests.size();
  63. // set test run map to false for all
  64. for (auto const& t : this->Tests) {
  65. this->TestRunningMap[t.first] = false;
  66. this->TestFinishMap[t.first] = false;
  67. }
  68. if (!this->CTest->GetShowOnly()) {
  69. this->ReadCostData();
  70. this->HasCycles = !this->CheckCycles();
  71. if (this->HasCycles) {
  72. return;
  73. }
  74. this->CreateTestCostList();
  75. }
  76. }
  77. // Set the max number of tests that can be run at the same time.
  78. void cmCTestMultiProcessHandler::SetParallelLevel(size_t level)
  79. {
  80. this->ParallelLevel = level < 1 ? 1 : level;
  81. }
  82. void cmCTestMultiProcessHandler::SetTestLoad(unsigned long load)
  83. {
  84. this->TestLoad = load;
  85. std::string fake_load_value;
  86. if (cmSystemTools::GetEnv("__CTEST_FAKE_LOAD_AVERAGE_FOR_TESTING",
  87. fake_load_value)) {
  88. if (!cmSystemTools::StringToULong(fake_load_value.c_str(),
  89. &this->FakeLoadForTesting)) {
  90. cmSystemTools::Error("Failed to parse fake load value: ",
  91. fake_load_value.c_str());
  92. }
  93. }
  94. }
  95. void cmCTestMultiProcessHandler::RunTests()
  96. {
  97. this->CheckResume();
  98. if (this->HasCycles) {
  99. return;
  100. }
  101. #ifdef CMAKE_UV_SIGNAL_HACK
  102. cmUVSignalHackRAII hackRAII;
  103. #endif
  104. this->TestHandler->SetMaxIndex(this->FindMaxIndex());
  105. uv_loop_init(&this->Loop);
  106. this->StartNextTests();
  107. uv_run(&this->Loop, UV_RUN_DEFAULT);
  108. uv_loop_close(&this->Loop);
  109. this->MarkFinished();
  110. this->UpdateCostData();
  111. }
  112. bool cmCTestMultiProcessHandler::StartTestProcess(int test)
  113. {
  114. if (this->HaveAffinity && this->Properties[test]->WantAffinity) {
  115. size_t needProcessors = this->GetProcessorsUsed(test);
  116. if (needProcessors > this->ProcessorsAvailable.size()) {
  117. return false;
  118. }
  119. std::vector<size_t> affinity;
  120. affinity.reserve(needProcessors);
  121. for (size_t i = 0; i < needProcessors; ++i) {
  122. auto p = this->ProcessorsAvailable.begin();
  123. affinity.push_back(*p);
  124. this->ProcessorsAvailable.erase(p);
  125. }
  126. this->Properties[test]->Affinity = std::move(affinity);
  127. }
  128. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  129. "test " << test << "\n", this->Quiet);
  130. this->TestRunningMap[test] = true; // mark the test as running
  131. // now remove the test itself
  132. this->EraseTest(test);
  133. this->RunningCount += GetProcessorsUsed(test);
  134. cmCTestRunTest* testRun = new cmCTestRunTest(*this);
  135. if (this->CTest->GetRepeatUntilFail()) {
  136. testRun->SetRunUntilFailOn();
  137. testRun->SetNumberOfRuns(this->CTest->GetTestRepeat());
  138. }
  139. testRun->SetIndex(test);
  140. testRun->SetTestProperties(this->Properties[test]);
  141. // Find any failed dependencies for this test. We assume the more common
  142. // scenario has no failed tests, so make it the outer loop.
  143. for (std::string const& f : *this->Failed) {
  144. if (this->Properties[test]->RequireSuccessDepends.find(f) !=
  145. this->Properties[test]->RequireSuccessDepends.end()) {
  146. testRun->AddFailedDependency(f);
  147. }
  148. }
  149. // Always lock the resources we'll be using, even if we fail to set the
  150. // working directory because FinishTestProcess() will try to unlock them
  151. this->LockResources(test);
  152. cmWorkingDirectory workdir(this->Properties[test]->Directory);
  153. if (workdir.Failed()) {
  154. testRun->StartFailure("Failed to change working directory to " +
  155. this->Properties[test]->Directory + " : " +
  156. std::strerror(workdir.GetLastResult()));
  157. } else {
  158. if (testRun->StartTest(this->Completed, this->Total)) {
  159. return true;
  160. }
  161. }
  162. this->FinishTestProcess(testRun, false);
  163. return false;
  164. }
  165. bool cmCTestMultiProcessHandler::CheckStopTimePassed()
  166. {
  167. if (!this->StopTimePassed) {
  168. std::chrono::system_clock::time_point stop_time =
  169. this->CTest->GetStopTime();
  170. if (stop_time != std::chrono::system_clock::time_point() &&
  171. stop_time <= std::chrono::system_clock::now()) {
  172. this->SetStopTimePassed();
  173. }
  174. }
  175. return this->StopTimePassed;
  176. }
  177. void cmCTestMultiProcessHandler::SetStopTimePassed()
  178. {
  179. if (!this->StopTimePassed) {
  180. cmCTestLog(this->CTest, ERROR_MESSAGE,
  181. "The stop time has been passed. "
  182. "Stopping all tests."
  183. << std::endl);
  184. this->StopTimePassed = true;
  185. }
  186. }
  187. void cmCTestMultiProcessHandler::LockResources(int index)
  188. {
  189. this->LockedResources.insert(
  190. this->Properties[index]->LockedResources.begin(),
  191. this->Properties[index]->LockedResources.end());
  192. if (this->Properties[index]->RunSerial) {
  193. this->SerialTestRunning = true;
  194. }
  195. }
  196. void cmCTestMultiProcessHandler::UnlockResources(int index)
  197. {
  198. for (std::string const& i : this->Properties[index]->LockedResources) {
  199. this->LockedResources.erase(i);
  200. }
  201. if (this->Properties[index]->RunSerial) {
  202. this->SerialTestRunning = false;
  203. }
  204. }
  205. void cmCTestMultiProcessHandler::EraseTest(int test)
  206. {
  207. this->Tests.erase(test);
  208. this->SortedTests.erase(
  209. std::find(this->SortedTests.begin(), this->SortedTests.end(), test));
  210. }
  211. inline size_t cmCTestMultiProcessHandler::GetProcessorsUsed(int test)
  212. {
  213. size_t processors = static_cast<int>(this->Properties[test]->Processors);
  214. // If processors setting is set higher than the -j
  215. // setting, we default to using all of the process slots.
  216. if (processors > this->ParallelLevel) {
  217. processors = this->ParallelLevel;
  218. }
  219. // Cap tests that want affinity to the maximum affinity available.
  220. if (this->HaveAffinity && processors > this->HaveAffinity &&
  221. this->Properties[test]->WantAffinity) {
  222. processors = this->HaveAffinity;
  223. }
  224. return processors;
  225. }
  226. std::string cmCTestMultiProcessHandler::GetName(int test)
  227. {
  228. return this->Properties[test]->Name;
  229. }
  230. bool cmCTestMultiProcessHandler::StartTest(int test)
  231. {
  232. // Check for locked resources
  233. for (std::string const& i : this->Properties[test]->LockedResources) {
  234. if (this->LockedResources.find(i) != this->LockedResources.end()) {
  235. return false;
  236. }
  237. }
  238. // if there are no depends left then run this test
  239. if (this->Tests[test].empty()) {
  240. return this->StartTestProcess(test);
  241. }
  242. // This test was not able to start because it is waiting
  243. // on depends to run
  244. return false;
  245. }
  246. void cmCTestMultiProcessHandler::StartNextTests()
  247. {
  248. if (this->TestLoadRetryTimer.get() != nullptr) {
  249. // This timer may be waiting to call StartNextTests again.
  250. // Since we have been called it is no longer needed.
  251. uv_timer_stop(this->TestLoadRetryTimer);
  252. }
  253. if (this->Tests.empty()) {
  254. this->TestLoadRetryTimer.reset();
  255. return;
  256. }
  257. if (this->CheckStopTimePassed()) {
  258. return;
  259. }
  260. size_t numToStart = 0;
  261. if (this->RunningCount < this->ParallelLevel) {
  262. numToStart = this->ParallelLevel - this->RunningCount;
  263. }
  264. if (numToStart == 0) {
  265. return;
  266. }
  267. // Don't start any new tests if one with the RUN_SERIAL property
  268. // is already running.
  269. if (this->SerialTestRunning) {
  270. return;
  271. }
  272. bool allTestsFailedTestLoadCheck = false;
  273. size_t minProcessorsRequired = this->ParallelLevel;
  274. std::string testWithMinProcessors;
  275. cmsys::SystemInformation info;
  276. unsigned long systemLoad = 0;
  277. size_t spareLoad = 0;
  278. if (this->TestLoad > 0) {
  279. // Activate possible wait.
  280. allTestsFailedTestLoadCheck = true;
  281. // Check for a fake load average value used in testing.
  282. if (this->FakeLoadForTesting > 0) {
  283. systemLoad = this->FakeLoadForTesting;
  284. // Drop the fake load for the next iteration to a value low enough
  285. // that the next iteration will start tests.
  286. this->FakeLoadForTesting = 1;
  287. }
  288. // If it's not set, look up the true load average.
  289. else {
  290. systemLoad = static_cast<unsigned long>(ceil(info.GetLoadAverage()));
  291. }
  292. spareLoad =
  293. (this->TestLoad > systemLoad ? this->TestLoad - systemLoad : 0);
  294. // Don't start more tests than the spare load can support.
  295. if (numToStart > spareLoad) {
  296. numToStart = spareLoad;
  297. }
  298. }
  299. TestList copy = this->SortedTests;
  300. for (auto const& test : copy) {
  301. // Take a nap if we're currently performing a RUN_SERIAL test.
  302. if (this->SerialTestRunning) {
  303. break;
  304. }
  305. // We can only start a RUN_SERIAL test if no other tests are also running.
  306. if (this->Properties[test]->RunSerial && this->RunningCount > 0) {
  307. continue;
  308. }
  309. size_t processors = GetProcessorsUsed(test);
  310. bool testLoadOk = true;
  311. if (this->TestLoad > 0) {
  312. if (processors <= spareLoad) {
  313. cmCTestLog(this->CTest, DEBUG,
  314. "OK to run " << GetName(test) << ", it requires "
  315. << processors << " procs & system load is: "
  316. << systemLoad << std::endl);
  317. allTestsFailedTestLoadCheck = false;
  318. } else {
  319. testLoadOk = false;
  320. }
  321. }
  322. if (processors <= minProcessorsRequired) {
  323. minProcessorsRequired = processors;
  324. testWithMinProcessors = GetName(test);
  325. }
  326. if (testLoadOk && processors <= numToStart && this->StartTest(test)) {
  327. numToStart -= processors;
  328. } else if (numToStart == 0) {
  329. break;
  330. }
  331. }
  332. if (allTestsFailedTestLoadCheck) {
  333. // Find out whether there are any non RUN_SERIAL tests left, so that the
  334. // correct warning may be displayed.
  335. bool onlyRunSerialTestsLeft = true;
  336. for (auto const& test : copy) {
  337. if (!this->Properties[test]->RunSerial) {
  338. onlyRunSerialTestsLeft = false;
  339. }
  340. }
  341. cmCTestLog(this->CTest, HANDLER_OUTPUT, "***** WAITING, ");
  342. if (this->SerialTestRunning) {
  343. cmCTestLog(this->CTest, HANDLER_OUTPUT,
  344. "Waiting for RUN_SERIAL test to finish.");
  345. } else if (onlyRunSerialTestsLeft) {
  346. cmCTestLog(this->CTest, HANDLER_OUTPUT,
  347. "Only RUN_SERIAL tests remain, awaiting available slot.");
  348. } else {
  349. /* clang-format off */
  350. cmCTestLog(this->CTest, HANDLER_OUTPUT,
  351. "System Load: " << systemLoad << ", "
  352. "Max Allowed Load: " << this->TestLoad << ", "
  353. "Smallest test " << testWithMinProcessors <<
  354. " requires " << minProcessorsRequired);
  355. /* clang-format on */
  356. }
  357. cmCTestLog(this->CTest, HANDLER_OUTPUT, "*****" << std::endl);
  358. // Wait between 1 and 5 seconds before trying again.
  359. unsigned int milliseconds = (cmSystemTools::RandomSeed() % 5 + 1) * 1000;
  360. if (this->FakeLoadForTesting) {
  361. milliseconds = 10;
  362. }
  363. if (this->TestLoadRetryTimer.get() == nullptr) {
  364. this->TestLoadRetryTimer.init(this->Loop, this);
  365. }
  366. this->TestLoadRetryTimer.start(
  367. &cmCTestMultiProcessHandler::OnTestLoadRetryCB, milliseconds, 0);
  368. }
  369. }
  370. void cmCTestMultiProcessHandler::OnTestLoadRetryCB(uv_timer_t* timer)
  371. {
  372. auto self = static_cast<cmCTestMultiProcessHandler*>(timer->data);
  373. self->StartNextTests();
  374. }
  375. void cmCTestMultiProcessHandler::FinishTestProcess(cmCTestRunTest* runner,
  376. bool started)
  377. {
  378. this->Completed++;
  379. int test = runner->GetIndex();
  380. auto properties = runner->GetTestProperties();
  381. bool testResult = runner->EndTest(this->Completed, this->Total, started);
  382. if (runner->TimedOutForStopTime()) {
  383. this->SetStopTimePassed();
  384. }
  385. if (started) {
  386. if (!this->StopTimePassed && runner->StartAgain(this->Completed)) {
  387. this->Completed--; // remove the completed test because run again
  388. return;
  389. }
  390. }
  391. if (testResult) {
  392. this->Passed->push_back(properties->Name);
  393. } else if (!properties->Disabled) {
  394. this->Failed->push_back(properties->Name);
  395. }
  396. for (auto& t : this->Tests) {
  397. t.second.erase(test);
  398. }
  399. this->TestFinishMap[test] = true;
  400. this->TestRunningMap[test] = false;
  401. this->WriteCheckpoint(test);
  402. this->UnlockResources(test);
  403. this->RunningCount -= GetProcessorsUsed(test);
  404. for (auto p : properties->Affinity) {
  405. this->ProcessorsAvailable.insert(p);
  406. }
  407. properties->Affinity.clear();
  408. delete runner;
  409. if (started) {
  410. this->StartNextTests();
  411. }
  412. }
  413. void cmCTestMultiProcessHandler::UpdateCostData()
  414. {
  415. std::string fname = this->CTest->GetCostDataFile();
  416. std::string tmpout = fname + ".tmp";
  417. cmsys::ofstream fout;
  418. fout.open(tmpout.c_str());
  419. PropertiesMap temp = this->Properties;
  420. if (cmSystemTools::FileExists(fname)) {
  421. cmsys::ifstream fin;
  422. fin.open(fname.c_str());
  423. std::string line;
  424. while (std::getline(fin, line)) {
  425. if (line == "---") {
  426. break;
  427. }
  428. std::vector<std::string> parts = cmSystemTools::SplitString(line, ' ');
  429. // Format: <name> <previous_runs> <avg_cost>
  430. if (parts.size() < 3) {
  431. break;
  432. }
  433. std::string name = parts[0];
  434. int prev = atoi(parts[1].c_str());
  435. float cost = static_cast<float>(atof(parts[2].c_str()));
  436. int index = this->SearchByName(name);
  437. if (index == -1) {
  438. // This test is not in memory. We just rewrite the entry
  439. fout << name << " " << prev << " " << cost << "\n";
  440. } else {
  441. // Update with our new average cost
  442. fout << name << " " << this->Properties[index]->PreviousRuns << " "
  443. << this->Properties[index]->Cost << "\n";
  444. temp.erase(index);
  445. }
  446. }
  447. fin.close();
  448. cmSystemTools::RemoveFile(fname);
  449. }
  450. // Add all tests not previously listed in the file
  451. for (auto const& i : temp) {
  452. fout << i.second->Name << " " << i.second->PreviousRuns << " "
  453. << i.second->Cost << "\n";
  454. }
  455. // Write list of failed tests
  456. fout << "---\n";
  457. for (std::string const& f : *this->Failed) {
  458. fout << f << "\n";
  459. }
  460. fout.close();
  461. cmSystemTools::RenameFile(tmpout.c_str(), fname.c_str());
  462. }
  463. void cmCTestMultiProcessHandler::ReadCostData()
  464. {
  465. std::string fname = this->CTest->GetCostDataFile();
  466. if (cmSystemTools::FileExists(fname, true)) {
  467. cmsys::ifstream fin;
  468. fin.open(fname.c_str());
  469. std::string line;
  470. while (std::getline(fin, line)) {
  471. if (line == "---") {
  472. break;
  473. }
  474. std::vector<std::string> parts = cmSystemTools::SplitString(line, ' ');
  475. // Probably an older version of the file, will be fixed next run
  476. if (parts.size() < 3) {
  477. fin.close();
  478. return;
  479. }
  480. std::string name = parts[0];
  481. int prev = atoi(parts[1].c_str());
  482. float cost = static_cast<float>(atof(parts[2].c_str()));
  483. int index = this->SearchByName(name);
  484. if (index == -1) {
  485. continue;
  486. }
  487. this->Properties[index]->PreviousRuns = prev;
  488. // When not running in parallel mode, don't use cost data
  489. if (this->ParallelLevel > 1 && this->Properties[index] &&
  490. this->Properties[index]->Cost == 0) {
  491. this->Properties[index]->Cost = cost;
  492. }
  493. }
  494. // Next part of the file is the failed tests
  495. while (std::getline(fin, line)) {
  496. if (!line.empty()) {
  497. this->LastTestsFailed.push_back(line);
  498. }
  499. }
  500. fin.close();
  501. }
  502. }
  503. int cmCTestMultiProcessHandler::SearchByName(std::string const& name)
  504. {
  505. int index = -1;
  506. for (auto const& p : this->Properties) {
  507. if (p.second->Name == name) {
  508. index = p.first;
  509. }
  510. }
  511. return index;
  512. }
  513. void cmCTestMultiProcessHandler::CreateTestCostList()
  514. {
  515. if (this->ParallelLevel > 1) {
  516. CreateParallelTestCostList();
  517. } else {
  518. CreateSerialTestCostList();
  519. }
  520. }
  521. void cmCTestMultiProcessHandler::CreateParallelTestCostList()
  522. {
  523. TestSet alreadySortedTests;
  524. std::list<TestSet> priorityStack;
  525. priorityStack.emplace_back();
  526. TestSet& topLevel = priorityStack.back();
  527. // In parallel test runs add previously failed tests to the front
  528. // of the cost list and queue other tests for further sorting
  529. for (auto const& t : this->Tests) {
  530. if (std::find(this->LastTestsFailed.begin(), this->LastTestsFailed.end(),
  531. this->Properties[t.first]->Name) !=
  532. this->LastTestsFailed.end()) {
  533. // If the test failed last time, it should be run first.
  534. this->SortedTests.push_back(t.first);
  535. alreadySortedTests.insert(t.first);
  536. } else {
  537. topLevel.insert(t.first);
  538. }
  539. }
  540. // In parallel test runs repeatedly move dependencies of the tests on
  541. // the current dependency level to the next level until no
  542. // further dependencies exist.
  543. while (!priorityStack.back().empty()) {
  544. TestSet& previousSet = priorityStack.back();
  545. priorityStack.emplace_back();
  546. TestSet& currentSet = priorityStack.back();
  547. for (auto const& i : previousSet) {
  548. TestSet const& dependencies = this->Tests[i];
  549. currentSet.insert(dependencies.begin(), dependencies.end());
  550. }
  551. for (auto const& i : currentSet) {
  552. previousSet.erase(i);
  553. }
  554. }
  555. // Remove the empty dependency level
  556. priorityStack.pop_back();
  557. // Reverse iterate over the different dependency levels (deepest first).
  558. // Sort tests within each level by COST and append them to the cost list.
  559. for (std::list<TestSet>::reverse_iterator i = priorityStack.rbegin();
  560. i != priorityStack.rend(); ++i) {
  561. TestSet const& currentSet = *i;
  562. TestComparator comp(this);
  563. TestList sortedCopy;
  564. sortedCopy.insert(sortedCopy.end(), currentSet.begin(), currentSet.end());
  565. std::stable_sort(sortedCopy.begin(), sortedCopy.end(), comp);
  566. for (auto const& j : sortedCopy) {
  567. if (alreadySortedTests.find(j) == alreadySortedTests.end()) {
  568. this->SortedTests.push_back(j);
  569. alreadySortedTests.insert(j);
  570. }
  571. }
  572. }
  573. }
  574. void cmCTestMultiProcessHandler::GetAllTestDependencies(int test,
  575. TestList& dependencies)
  576. {
  577. TestSet const& dependencySet = this->Tests[test];
  578. for (int i : dependencySet) {
  579. GetAllTestDependencies(i, dependencies);
  580. dependencies.push_back(i);
  581. }
  582. }
  583. void cmCTestMultiProcessHandler::CreateSerialTestCostList()
  584. {
  585. TestList presortedList;
  586. for (auto const& i : this->Tests) {
  587. presortedList.push_back(i.first);
  588. }
  589. TestComparator comp(this);
  590. std::stable_sort(presortedList.begin(), presortedList.end(), comp);
  591. TestSet alreadySortedTests;
  592. for (int test : presortedList) {
  593. if (alreadySortedTests.find(test) != alreadySortedTests.end()) {
  594. continue;
  595. }
  596. TestList dependencies;
  597. GetAllTestDependencies(test, dependencies);
  598. for (int testDependency : dependencies) {
  599. if (alreadySortedTests.find(testDependency) ==
  600. alreadySortedTests.end()) {
  601. alreadySortedTests.insert(testDependency);
  602. this->SortedTests.push_back(testDependency);
  603. }
  604. }
  605. alreadySortedTests.insert(test);
  606. this->SortedTests.push_back(test);
  607. }
  608. }
  609. void cmCTestMultiProcessHandler::WriteCheckpoint(int index)
  610. {
  611. std::string fname =
  612. this->CTest->GetBinaryDir() + "/Testing/Temporary/CTestCheckpoint.txt";
  613. cmsys::ofstream fout;
  614. fout.open(fname.c_str(), std::ios::app);
  615. fout << index << "\n";
  616. fout.close();
  617. }
  618. void cmCTestMultiProcessHandler::MarkFinished()
  619. {
  620. std::string fname =
  621. this->CTest->GetBinaryDir() + "/Testing/Temporary/CTestCheckpoint.txt";
  622. cmSystemTools::RemoveFile(fname);
  623. }
  624. // For ShowOnly mode
  625. void cmCTestMultiProcessHandler::PrintTestList()
  626. {
  627. this->TestHandler->SetMaxIndex(this->FindMaxIndex());
  628. int count = 0;
  629. for (auto& it : this->Properties) {
  630. count++;
  631. cmCTestTestHandler::cmCTestTestProperties& p = *it.second;
  632. // Don't worry if this fails, we are only showing the test list, not
  633. // running the tests
  634. cmWorkingDirectory workdir(p.Directory);
  635. cmCTestRunTest testRun(*this);
  636. testRun.SetIndex(p.Index);
  637. testRun.SetTestProperties(&p);
  638. testRun.ComputeArguments(); // logs the command in verbose mode
  639. if (!p.Labels.empty()) // print the labels
  640. {
  641. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  642. "Labels:", this->Quiet);
  643. }
  644. for (std::string const& label : p.Labels) {
  645. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, " " << label,
  646. this->Quiet);
  647. }
  648. if (!p.Labels.empty()) // print the labels
  649. {
  650. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, std::endl,
  651. this->Quiet);
  652. }
  653. if (this->TestHandler->MemCheck) {
  654. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, " Memory Check",
  655. this->Quiet);
  656. } else {
  657. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, " Test", this->Quiet);
  658. }
  659. std::ostringstream indexStr;
  660. indexStr << " #" << p.Index << ":";
  661. cmCTestOptionalLog(
  662. this->CTest, HANDLER_OUTPUT,
  663. std::setw(3 + getNumWidth(this->TestHandler->GetMaxIndex()))
  664. << indexStr.str(),
  665. this->Quiet);
  666. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, " " << p.Name,
  667. this->Quiet);
  668. if (p.Disabled) {
  669. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, " (Disabled)",
  670. this->Quiet);
  671. }
  672. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, std::endl, this->Quiet);
  673. }
  674. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  675. std::endl
  676. << "Total Tests: " << this->Total << std::endl,
  677. this->Quiet);
  678. }
  679. void cmCTestMultiProcessHandler::PrintLabels()
  680. {
  681. std::set<std::string> allLabels;
  682. for (auto& it : this->Properties) {
  683. cmCTestTestHandler::cmCTestTestProperties& p = *it.second;
  684. allLabels.insert(p.Labels.begin(), p.Labels.end());
  685. }
  686. if (!allLabels.empty()) {
  687. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, "All Labels:" << std::endl,
  688. this->Quiet);
  689. } else {
  690. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  691. "No Labels Exist" << std::endl, this->Quiet);
  692. }
  693. for (std::string const& label : allLabels) {
  694. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, " " << label << std::endl,
  695. this->Quiet);
  696. }
  697. }
  698. void cmCTestMultiProcessHandler::CheckResume()
  699. {
  700. std::string fname =
  701. this->CTest->GetBinaryDir() + "/Testing/Temporary/CTestCheckpoint.txt";
  702. if (this->CTest->GetFailover()) {
  703. if (cmSystemTools::FileExists(fname, true)) {
  704. *this->TestHandler->LogFile
  705. << "Resuming previously interrupted test set" << std::endl
  706. << "----------------------------------------------------------"
  707. << std::endl;
  708. cmsys::ifstream fin;
  709. fin.open(fname.c_str());
  710. std::string line;
  711. while (std::getline(fin, line)) {
  712. int index = atoi(line.c_str());
  713. this->RemoveTest(index);
  714. }
  715. fin.close();
  716. }
  717. } else if (cmSystemTools::FileExists(fname, true)) {
  718. cmSystemTools::RemoveFile(fname);
  719. }
  720. }
  721. void cmCTestMultiProcessHandler::RemoveTest(int index)
  722. {
  723. this->EraseTest(index);
  724. this->Properties.erase(index);
  725. this->TestRunningMap[index] = false;
  726. this->TestFinishMap[index] = true;
  727. this->Completed++;
  728. }
  729. int cmCTestMultiProcessHandler::FindMaxIndex()
  730. {
  731. int max = 0;
  732. for (auto const& i : this->Tests) {
  733. if (i.first > max) {
  734. max = i.first;
  735. }
  736. }
  737. return max;
  738. }
  739. // Returns true if no cycles exist in the dependency graph
  740. bool cmCTestMultiProcessHandler::CheckCycles()
  741. {
  742. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  743. "Checking test dependency graph..." << std::endl,
  744. this->Quiet);
  745. for (auto const& it : this->Tests) {
  746. // DFS from each element to itself
  747. int root = it.first;
  748. std::set<int> visited;
  749. std::stack<int> s;
  750. s.push(root);
  751. while (!s.empty()) {
  752. int test = s.top();
  753. s.pop();
  754. if (visited.insert(test).second) {
  755. for (auto const& d : this->Tests[test]) {
  756. if (d == root) {
  757. // cycle exists
  758. cmCTestLog(
  759. this->CTest, ERROR_MESSAGE,
  760. "Error: a cycle exists in the test dependency graph "
  761. "for the test \""
  762. << this->Properties[root]->Name
  763. << "\".\nPlease fix the cycle and run ctest again.\n");
  764. return false;
  765. }
  766. s.push(d);
  767. }
  768. }
  769. }
  770. }
  771. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  772. "Checking test dependency graph end" << std::endl,
  773. this->Quiet);
  774. return true;
  775. }