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