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