cmCTestMultiProcessHandler.cxx 43 KB

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