cmCTestMultiProcessHandler.cxx 46 KB

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