cmCTestMultiProcessHandler.cxx 36 KB

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