cmCTestMultiProcessHandler.cxx 25 KB

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