cmCTestMultiProcessHandler.cxx 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528
  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 && !this->SerialTestRunning &&
  477. ti != this->OrderedTests.end()) {
  478. // Increment the test iterator now because the current list
  479. // entry may be deleted below.
  480. int test = *ti++;
  481. // We can only start a RUN_SERIAL test if no other tests are also
  482. // running.
  483. if (this->Properties[test]->RunSerial && this->RunningCount > 0) {
  484. continue;
  485. }
  486. size_t processors = this->GetProcessorsUsed(test);
  487. if (this->TestLoad > 0) {
  488. // Exclude tests that are too big to fit in the spare load.
  489. if (processors > spareLoad) {
  490. // Keep track of the smallest excluded test to report in message below.
  491. if (processors <= minProcessorsRequired) {
  492. minProcessorsRequired = processors;
  493. testWithMinProcessors = this->GetName(test);
  494. }
  495. continue;
  496. }
  497. // We found a test that fits in the spare load.
  498. allTestsFailedTestLoadCheck = false;
  499. cmCTestLog(this->CTest, DEBUG,
  500. "OK to run "
  501. << this->GetName(test) << ", it requires " << processors
  502. << " procs & system load is: " << systemLoad << std::endl);
  503. }
  504. // Exclude tests that are too big to fit in the concurrency limit.
  505. if (processors > numToStart) {
  506. continue;
  507. }
  508. if (this->StartTest(test)) {
  509. numToStart -= processors;
  510. }
  511. }
  512. if (allTestsFailedTestLoadCheck) {
  513. // Find out whether there are any non RUN_SERIAL tests left, so that the
  514. // correct warning may be displayed.
  515. bool onlyRunSerialTestsLeft = true;
  516. for (auto const& t : this->PendingTests) {
  517. if (!this->Properties[t.first]->RunSerial) {
  518. onlyRunSerialTestsLeft = false;
  519. }
  520. }
  521. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, "***** WAITING, ");
  522. if (this->SerialTestRunning) {
  523. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  524. "Waiting for RUN_SERIAL test to finish.");
  525. } else if (onlyRunSerialTestsLeft) {
  526. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  527. "Only RUN_SERIAL tests remain, awaiting available slot.");
  528. } else if (!testWithMinProcessors.empty()) {
  529. /* clang-format off */
  530. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  531. "System Load: " << systemLoad << ", "
  532. "Max Allowed Load: " << this->TestLoad << ", "
  533. "Smallest test " << testWithMinProcessors <<
  534. " requires " << minProcessorsRequired);
  535. /* clang-format on */
  536. } else {
  537. /* clang-format off */
  538. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  539. "System Load: " << systemLoad << ", "
  540. "Max Allowed Load: " << this->TestLoad);
  541. /* clang-format on */
  542. }
  543. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, "*****" << std::endl);
  544. // Wait between 1 and 5 seconds before trying again.
  545. unsigned int milliseconds = (cmSystemTools::RandomSeed() % 5 + 1) * 1000;
  546. if (this->FakeLoadForTesting) {
  547. milliseconds = 10;
  548. }
  549. if (this->TestLoadRetryTimer.get() == nullptr) {
  550. this->TestLoadRetryTimer.init(*this->Loop, this);
  551. }
  552. this->TestLoadRetryTimer.start(
  553. &cmCTestMultiProcessHandler::OnTestLoadRetryCB, milliseconds, 0);
  554. }
  555. }
  556. void cmCTestMultiProcessHandler::OnTestLoadRetryCB(uv_timer_t* timer)
  557. {
  558. auto* self = static_cast<cmCTestMultiProcessHandler*>(timer->data);
  559. self->StartNextTests();
  560. }
  561. void cmCTestMultiProcessHandler::FinishTestProcess(
  562. std::unique_ptr<cmCTestRunTest> runner, bool started)
  563. {
  564. this->Completed++;
  565. int test = runner->GetIndex();
  566. auto* properties = runner->GetTestProperties();
  567. cmCTestRunTest::EndTestResult testResult =
  568. runner->EndTest(this->Completed, this->Total, started);
  569. if (testResult.StopTimePassed) {
  570. this->SetStopTimePassed();
  571. }
  572. if (started) {
  573. if (!this->StopTimePassed &&
  574. cmCTestRunTest::StartAgain(std::move(runner), this->Completed)) {
  575. this->Completed--; // remove the completed test because run again
  576. return;
  577. }
  578. }
  579. if (testResult.Passed) {
  580. this->Passed->push_back(properties->Name);
  581. } else if (!properties->Disabled) {
  582. this->Failed->push_back(properties->Name);
  583. }
  584. for (auto& t : this->PendingTests) {
  585. t.second.Depends.erase(test);
  586. }
  587. this->WriteCheckpoint(test);
  588. this->DeallocateResources(test);
  589. this->UnlockResources(test);
  590. this->RunningCount -= this->GetProcessorsUsed(test);
  591. for (auto p : properties->Affinity) {
  592. this->ProcessorsAvailable.insert(p);
  593. }
  594. properties->Affinity.clear();
  595. runner.reset();
  596. if (started) {
  597. this->StartNextTests();
  598. }
  599. }
  600. void cmCTestMultiProcessHandler::UpdateCostData()
  601. {
  602. std::string fname = this->CTest->GetCostDataFile();
  603. std::string tmpout = fname + ".tmp";
  604. cmsys::ofstream fout;
  605. fout.open(tmpout.c_str());
  606. PropertiesMap temp = this->Properties;
  607. if (cmSystemTools::FileExists(fname)) {
  608. cmsys::ifstream fin;
  609. fin.open(fname.c_str());
  610. std::string line;
  611. while (std::getline(fin, line)) {
  612. if (line == "---") {
  613. break;
  614. }
  615. std::vector<std::string> parts = cmSystemTools::SplitString(line, ' ');
  616. // Format: <name> <previous_runs> <avg_cost>
  617. if (parts.size() < 3) {
  618. break;
  619. }
  620. std::string name = parts[0];
  621. int prev = atoi(parts[1].c_str());
  622. float cost = static_cast<float>(atof(parts[2].c_str()));
  623. int index = this->SearchByName(name);
  624. if (index == -1) {
  625. // This test is not in memory. We just rewrite the entry
  626. fout << name << " " << prev << " " << cost << "\n";
  627. } else {
  628. // Update with our new average cost
  629. fout << name << " " << this->Properties[index]->PreviousRuns << " "
  630. << this->Properties[index]->Cost << "\n";
  631. temp.erase(index);
  632. }
  633. }
  634. fin.close();
  635. cmSystemTools::RemoveFile(fname);
  636. }
  637. // Add all tests not previously listed in the file
  638. for (auto const& i : temp) {
  639. fout << i.second->Name << " " << i.second->PreviousRuns << " "
  640. << i.second->Cost << "\n";
  641. }
  642. // Write list of failed tests
  643. fout << "---\n";
  644. for (std::string const& f : *this->Failed) {
  645. fout << f << "\n";
  646. }
  647. fout.close();
  648. cmSystemTools::RenameFile(tmpout, fname);
  649. }
  650. void cmCTestMultiProcessHandler::ReadCostData()
  651. {
  652. std::string fname = this->CTest->GetCostDataFile();
  653. if (cmSystemTools::FileExists(fname, true)) {
  654. cmsys::ifstream fin;
  655. fin.open(fname.c_str());
  656. std::string line;
  657. while (std::getline(fin, line)) {
  658. if (line == "---") {
  659. break;
  660. }
  661. std::vector<std::string> parts = cmSystemTools::SplitString(line, ' ');
  662. // Probably an older version of the file, will be fixed next run
  663. if (parts.size() < 3) {
  664. fin.close();
  665. return;
  666. }
  667. std::string name = parts[0];
  668. int prev = atoi(parts[1].c_str());
  669. float cost = static_cast<float>(atof(parts[2].c_str()));
  670. int index = this->SearchByName(name);
  671. if (index == -1) {
  672. continue;
  673. }
  674. this->Properties[index]->PreviousRuns = prev;
  675. // When not running in parallel mode, don't use cost data
  676. if (this->ParallelLevel > 1 && this->Properties[index] &&
  677. this->Properties[index]->Cost == 0) {
  678. this->Properties[index]->Cost = cost;
  679. }
  680. }
  681. // Next part of the file is the failed tests
  682. while (std::getline(fin, line)) {
  683. if (!line.empty()) {
  684. this->LastTestsFailed.push_back(line);
  685. }
  686. }
  687. fin.close();
  688. }
  689. }
  690. int cmCTestMultiProcessHandler::SearchByName(std::string const& name)
  691. {
  692. int index = -1;
  693. for (auto const& p : this->Properties) {
  694. if (p.second->Name == name) {
  695. index = p.first;
  696. }
  697. }
  698. return index;
  699. }
  700. void cmCTestMultiProcessHandler::CreateTestCostList()
  701. {
  702. if (this->ParallelLevel > 1) {
  703. this->CreateParallelTestCostList();
  704. } else {
  705. this->CreateSerialTestCostList();
  706. }
  707. }
  708. void cmCTestMultiProcessHandler::CreateParallelTestCostList()
  709. {
  710. TestSet alreadyOrderedTests;
  711. std::list<TestSet> priorityStack;
  712. priorityStack.emplace_back();
  713. TestSet& topLevel = priorityStack.back();
  714. // In parallel test runs add previously failed tests to the front
  715. // of the cost list and queue other tests for further sorting
  716. for (auto const& t : this->PendingTests) {
  717. if (cm::contains(this->LastTestsFailed, this->Properties[t.first]->Name)) {
  718. // If the test failed last time, it should be run first.
  719. this->OrderedTests.push_back(t.first);
  720. alreadyOrderedTests.insert(t.first);
  721. } else {
  722. topLevel.insert(t.first);
  723. }
  724. }
  725. // In parallel test runs repeatedly move dependencies of the tests on
  726. // the current dependency level to the next level until no
  727. // further dependencies exist.
  728. while (!priorityStack.back().empty()) {
  729. TestSet& previousSet = priorityStack.back();
  730. priorityStack.emplace_back();
  731. TestSet& currentSet = priorityStack.back();
  732. for (auto const& i : previousSet) {
  733. TestSet const& dependencies = this->PendingTests[i].Depends;
  734. currentSet.insert(dependencies.begin(), dependencies.end());
  735. }
  736. for (auto const& i : currentSet) {
  737. previousSet.erase(i);
  738. }
  739. }
  740. // Remove the empty dependency level
  741. priorityStack.pop_back();
  742. // Reverse iterate over the different dependency levels (deepest first).
  743. // Sort tests within each level by COST and append them to the cost list.
  744. for (TestSet const& currentSet : cmReverseRange(priorityStack)) {
  745. TestList sortedCopy;
  746. cm::append(sortedCopy, currentSet);
  747. std::stable_sort(sortedCopy.begin(), sortedCopy.end(),
  748. TestComparator(this));
  749. for (auto const& j : sortedCopy) {
  750. if (!cm::contains(alreadyOrderedTests, j)) {
  751. this->OrderedTests.push_back(j);
  752. alreadyOrderedTests.insert(j);
  753. }
  754. }
  755. }
  756. }
  757. void cmCTestMultiProcessHandler::GetAllTestDependencies(int test,
  758. TestList& dependencies)
  759. {
  760. TestSet const& dependencySet = this->PendingTests[test].Depends;
  761. for (int i : dependencySet) {
  762. this->GetAllTestDependencies(i, dependencies);
  763. dependencies.push_back(i);
  764. }
  765. }
  766. void cmCTestMultiProcessHandler::CreateSerialTestCostList()
  767. {
  768. TestList presortedList;
  769. for (auto const& i : this->PendingTests) {
  770. presortedList.push_back(i.first);
  771. }
  772. std::stable_sort(presortedList.begin(), presortedList.end(),
  773. TestComparator(this));
  774. TestSet alreadyOrderedTests;
  775. for (int test : presortedList) {
  776. if (cm::contains(alreadyOrderedTests, test)) {
  777. continue;
  778. }
  779. TestList dependencies;
  780. this->GetAllTestDependencies(test, dependencies);
  781. for (int testDependency : dependencies) {
  782. if (!cm::contains(alreadyOrderedTests, testDependency)) {
  783. alreadyOrderedTests.insert(testDependency);
  784. this->OrderedTests.push_back(testDependency);
  785. }
  786. }
  787. alreadyOrderedTests.insert(test);
  788. this->OrderedTests.push_back(test);
  789. }
  790. }
  791. void cmCTestMultiProcessHandler::WriteCheckpoint(int index)
  792. {
  793. std::string fname =
  794. this->CTest->GetBinaryDir() + "/Testing/Temporary/CTestCheckpoint.txt";
  795. cmsys::ofstream fout;
  796. fout.open(fname.c_str(), std::ios::app);
  797. fout << index << "\n";
  798. fout.close();
  799. }
  800. void cmCTestMultiProcessHandler::MarkFinished()
  801. {
  802. std::string fname =
  803. this->CTest->GetBinaryDir() + "/Testing/Temporary/CTestCheckpoint.txt";
  804. cmSystemTools::RemoveFile(fname);
  805. }
  806. static Json::Value DumpToJsonArray(const std::set<std::string>& values)
  807. {
  808. Json::Value jsonArray = Json::arrayValue;
  809. for (const auto& it : values) {
  810. jsonArray.append(it);
  811. }
  812. return jsonArray;
  813. }
  814. static Json::Value DumpToJsonArray(const std::vector<std::string>& values)
  815. {
  816. Json::Value jsonArray = Json::arrayValue;
  817. for (const auto& it : values) {
  818. jsonArray.append(it);
  819. }
  820. return jsonArray;
  821. }
  822. static Json::Value DumpRegExToJsonArray(
  823. const std::vector<std::pair<cmsys::RegularExpression, std::string>>& values)
  824. {
  825. Json::Value jsonArray = Json::arrayValue;
  826. for (const auto& it : values) {
  827. jsonArray.append(it.second);
  828. }
  829. return jsonArray;
  830. }
  831. static Json::Value DumpMeasurementToJsonArray(
  832. const std::map<std::string, std::string>& values)
  833. {
  834. Json::Value jsonArray = Json::arrayValue;
  835. for (const auto& it : values) {
  836. Json::Value measurement = Json::objectValue;
  837. measurement["measurement"] = it.first;
  838. measurement["value"] = it.second;
  839. jsonArray.append(measurement);
  840. }
  841. return jsonArray;
  842. }
  843. static Json::Value DumpTimeoutAfterMatch(
  844. cmCTestTestHandler::cmCTestTestProperties& testProperties)
  845. {
  846. Json::Value timeoutAfterMatch = Json::objectValue;
  847. timeoutAfterMatch["timeout"] = testProperties.AlternateTimeout.count();
  848. timeoutAfterMatch["regex"] =
  849. DumpRegExToJsonArray(testProperties.TimeoutRegularExpressions);
  850. return timeoutAfterMatch;
  851. }
  852. static Json::Value DumpResourceGroupsToJsonArray(
  853. const std::vector<
  854. std::vector<cmCTestTestHandler::cmCTestTestResourceRequirement>>&
  855. resourceGroups)
  856. {
  857. Json::Value jsonResourceGroups = Json::arrayValue;
  858. for (auto const& it : resourceGroups) {
  859. Json::Value jsonResourceGroup = Json::objectValue;
  860. Json::Value requirements = Json::arrayValue;
  861. for (auto const& it2 : it) {
  862. Json::Value res = Json::objectValue;
  863. res[".type"] = it2.ResourceType;
  864. // res[".units"] = it2.UnitsNeeded; // Intentionally commented out
  865. res["slots"] = it2.SlotsNeeded;
  866. requirements.append(res);
  867. }
  868. jsonResourceGroup["requirements"] = requirements;
  869. jsonResourceGroups.append(jsonResourceGroup);
  870. }
  871. return jsonResourceGroups;
  872. }
  873. static Json::Value DumpCTestProperty(std::string const& name,
  874. Json::Value value)
  875. {
  876. Json::Value property = Json::objectValue;
  877. property["name"] = name;
  878. property["value"] = std::move(value);
  879. return property;
  880. }
  881. static Json::Value DumpCTestProperties(
  882. cmCTestTestHandler::cmCTestTestProperties& testProperties)
  883. {
  884. Json::Value properties = Json::arrayValue;
  885. if (!testProperties.AttachOnFail.empty()) {
  886. properties.append(DumpCTestProperty(
  887. "ATTACHED_FILES_ON_FAIL", DumpToJsonArray(testProperties.AttachOnFail)));
  888. }
  889. if (!testProperties.AttachedFiles.empty()) {
  890. properties.append(DumpCTestProperty(
  891. "ATTACHED_FILES", DumpToJsonArray(testProperties.AttachedFiles)));
  892. }
  893. if (testProperties.Cost != 0.0f) {
  894. properties.append(
  895. DumpCTestProperty("COST", static_cast<double>(testProperties.Cost)));
  896. }
  897. if (!testProperties.Depends.empty()) {
  898. properties.append(
  899. DumpCTestProperty("DEPENDS", DumpToJsonArray(testProperties.Depends)));
  900. }
  901. if (testProperties.Disabled) {
  902. properties.append(DumpCTestProperty("DISABLED", testProperties.Disabled));
  903. }
  904. if (!testProperties.Environment.empty()) {
  905. properties.append(DumpCTestProperty(
  906. "ENVIRONMENT", DumpToJsonArray(testProperties.Environment)));
  907. }
  908. if (!testProperties.EnvironmentModification.empty()) {
  909. properties.append(DumpCTestProperty(
  910. "ENVIRONMENT_MODIFICATION",
  911. DumpToJsonArray(testProperties.EnvironmentModification)));
  912. }
  913. if (!testProperties.ErrorRegularExpressions.empty()) {
  914. properties.append(DumpCTestProperty(
  915. "FAIL_REGULAR_EXPRESSION",
  916. DumpRegExToJsonArray(testProperties.ErrorRegularExpressions)));
  917. }
  918. if (!testProperties.SkipRegularExpressions.empty()) {
  919. properties.append(DumpCTestProperty(
  920. "SKIP_REGULAR_EXPRESSION",
  921. DumpRegExToJsonArray(testProperties.SkipRegularExpressions)));
  922. }
  923. if (!testProperties.FixturesCleanup.empty()) {
  924. properties.append(DumpCTestProperty(
  925. "FIXTURES_CLEANUP", DumpToJsonArray(testProperties.FixturesCleanup)));
  926. }
  927. if (!testProperties.FixturesRequired.empty()) {
  928. properties.append(DumpCTestProperty(
  929. "FIXTURES_REQUIRED", DumpToJsonArray(testProperties.FixturesRequired)));
  930. }
  931. if (!testProperties.FixturesSetup.empty()) {
  932. properties.append(DumpCTestProperty(
  933. "FIXTURES_SETUP", DumpToJsonArray(testProperties.FixturesSetup)));
  934. }
  935. if (!testProperties.Labels.empty()) {
  936. properties.append(
  937. DumpCTestProperty("LABELS", DumpToJsonArray(testProperties.Labels)));
  938. }
  939. if (!testProperties.Measurements.empty()) {
  940. properties.append(DumpCTestProperty(
  941. "MEASUREMENT", DumpMeasurementToJsonArray(testProperties.Measurements)));
  942. }
  943. if (!testProperties.RequiredRegularExpressions.empty()) {
  944. properties.append(DumpCTestProperty(
  945. "PASS_REGULAR_EXPRESSION",
  946. DumpRegExToJsonArray(testProperties.RequiredRegularExpressions)));
  947. }
  948. if (!testProperties.ResourceGroups.empty()) {
  949. properties.append(DumpCTestProperty(
  950. "RESOURCE_GROUPS",
  951. DumpResourceGroupsToJsonArray(testProperties.ResourceGroups)));
  952. }
  953. if (testProperties.WantAffinity) {
  954. properties.append(
  955. DumpCTestProperty("PROCESSOR_AFFINITY", testProperties.WantAffinity));
  956. }
  957. if (testProperties.Processors != 1) {
  958. properties.append(
  959. DumpCTestProperty("PROCESSORS", testProperties.Processors));
  960. }
  961. if (!testProperties.RequiredFiles.empty()) {
  962. properties.append(DumpCTestProperty(
  963. "REQUIRED_FILES", DumpToJsonArray(testProperties.RequiredFiles)));
  964. }
  965. if (!testProperties.LockedResources.empty()) {
  966. properties.append(DumpCTestProperty(
  967. "RESOURCE_LOCK", DumpToJsonArray(testProperties.LockedResources)));
  968. }
  969. if (testProperties.RunSerial) {
  970. properties.append(
  971. DumpCTestProperty("RUN_SERIAL", testProperties.RunSerial));
  972. }
  973. if (testProperties.SkipReturnCode != -1) {
  974. properties.append(
  975. DumpCTestProperty("SKIP_RETURN_CODE", testProperties.SkipReturnCode));
  976. }
  977. if (testProperties.Timeout) {
  978. properties.append(
  979. DumpCTestProperty("TIMEOUT", testProperties.Timeout->count()));
  980. }
  981. if (!testProperties.TimeoutRegularExpressions.empty()) {
  982. properties.append(DumpCTestProperty(
  983. "TIMEOUT_AFTER_MATCH", DumpTimeoutAfterMatch(testProperties)));
  984. }
  985. if (testProperties.WillFail) {
  986. properties.append(DumpCTestProperty("WILL_FAIL", testProperties.WillFail));
  987. }
  988. if (!testProperties.Directory.empty()) {
  989. properties.append(
  990. DumpCTestProperty("WORKING_DIRECTORY", testProperties.Directory));
  991. }
  992. return properties;
  993. }
  994. class BacktraceData
  995. {
  996. std::unordered_map<std::string, Json::ArrayIndex> CommandMap;
  997. std::unordered_map<std::string, Json::ArrayIndex> FileMap;
  998. std::unordered_map<cmListFileContext const*, Json::ArrayIndex> NodeMap;
  999. Json::Value Commands = Json::arrayValue;
  1000. Json::Value Files = Json::arrayValue;
  1001. Json::Value Nodes = Json::arrayValue;
  1002. Json::ArrayIndex AddCommand(std::string const& command)
  1003. {
  1004. auto i = this->CommandMap.find(command);
  1005. if (i == this->CommandMap.end()) {
  1006. i = this->CommandMap.emplace(command, this->Commands.size()).first;
  1007. this->Commands.append(command);
  1008. }
  1009. return i->second;
  1010. }
  1011. Json::ArrayIndex AddFile(std::string const& file)
  1012. {
  1013. auto i = this->FileMap.find(file);
  1014. if (i == this->FileMap.end()) {
  1015. i = this->FileMap.emplace(file, this->Files.size()).first;
  1016. this->Files.append(file);
  1017. }
  1018. return i->second;
  1019. }
  1020. public:
  1021. bool Add(cmListFileBacktrace const& bt, Json::ArrayIndex& index);
  1022. Json::Value Dump();
  1023. };
  1024. bool BacktraceData::Add(cmListFileBacktrace const& bt, Json::ArrayIndex& index)
  1025. {
  1026. if (bt.Empty()) {
  1027. return false;
  1028. }
  1029. cmListFileContext const* top = &bt.Top();
  1030. auto found = this->NodeMap.find(top);
  1031. if (found != this->NodeMap.end()) {
  1032. index = found->second;
  1033. return true;
  1034. }
  1035. Json::Value entry = Json::objectValue;
  1036. entry["file"] = this->AddFile(top->FilePath);
  1037. if (top->Line) {
  1038. entry["line"] = static_cast<int>(top->Line);
  1039. }
  1040. if (!top->Name.empty()) {
  1041. entry["command"] = this->AddCommand(top->Name);
  1042. }
  1043. Json::ArrayIndex parent;
  1044. if (this->Add(bt.Pop(), parent)) {
  1045. entry["parent"] = parent;
  1046. }
  1047. index = this->NodeMap[top] = this->Nodes.size();
  1048. this->Nodes.append(std::move(entry)); // NOLINT(*)
  1049. return true;
  1050. }
  1051. Json::Value BacktraceData::Dump()
  1052. {
  1053. Json::Value backtraceGraph;
  1054. this->CommandMap.clear();
  1055. this->FileMap.clear();
  1056. this->NodeMap.clear();
  1057. backtraceGraph["commands"] = std::move(this->Commands);
  1058. backtraceGraph["files"] = std::move(this->Files);
  1059. backtraceGraph["nodes"] = std::move(this->Nodes);
  1060. return backtraceGraph;
  1061. }
  1062. static void AddBacktrace(BacktraceData& backtraceGraph, Json::Value& object,
  1063. cmListFileBacktrace const& bt)
  1064. {
  1065. Json::ArrayIndex backtrace;
  1066. if (backtraceGraph.Add(bt, backtrace)) {
  1067. object["backtrace"] = backtrace;
  1068. }
  1069. }
  1070. static Json::Value DumpCTestInfo(
  1071. cmCTestRunTest& testRun,
  1072. cmCTestTestHandler::cmCTestTestProperties& testProperties,
  1073. BacktraceData& backtraceGraph)
  1074. {
  1075. Json::Value testInfo = Json::objectValue;
  1076. // test name should always be present
  1077. testInfo["name"] = testProperties.Name;
  1078. std::string const& config = testRun.GetCTest()->GetConfigType();
  1079. if (!config.empty()) {
  1080. testInfo["config"] = config;
  1081. }
  1082. std::string const& command = testRun.GetActualCommand();
  1083. if (!command.empty()) {
  1084. std::vector<std::string> commandAndArgs;
  1085. commandAndArgs.push_back(command);
  1086. const std::vector<std::string>& args = testRun.GetArguments();
  1087. if (!args.empty()) {
  1088. commandAndArgs.reserve(args.size() + 1);
  1089. cm::append(commandAndArgs, args);
  1090. }
  1091. testInfo["command"] = DumpToJsonArray(commandAndArgs);
  1092. }
  1093. Json::Value properties = DumpCTestProperties(testProperties);
  1094. if (!properties.empty()) {
  1095. testInfo["properties"] = properties;
  1096. }
  1097. if (!testProperties.Backtrace.Empty()) {
  1098. AddBacktrace(backtraceGraph, testInfo, testProperties.Backtrace);
  1099. }
  1100. return testInfo;
  1101. }
  1102. static Json::Value DumpVersion(int major, int minor)
  1103. {
  1104. Json::Value version = Json::objectValue;
  1105. version["major"] = major;
  1106. version["minor"] = minor;
  1107. return version;
  1108. }
  1109. void cmCTestMultiProcessHandler::PrintOutputAsJson()
  1110. {
  1111. this->TestHandler->SetMaxIndex(this->FindMaxIndex());
  1112. Json::Value result = Json::objectValue;
  1113. result["kind"] = "ctestInfo";
  1114. result["version"] = DumpVersion(1, 0);
  1115. BacktraceData backtraceGraph;
  1116. Json::Value tests = Json::arrayValue;
  1117. for (auto& it : this->Properties) {
  1118. cmCTestTestHandler::cmCTestTestProperties& p = *it.second;
  1119. // Don't worry if this fails, we are only showing the test list, not
  1120. // running the tests
  1121. cmWorkingDirectory workdir(p.Directory);
  1122. cmCTestRunTest testRun(*this, p.Index);
  1123. testRun.ComputeArguments();
  1124. // Skip tests not available in this configuration.
  1125. if (p.Args.size() >= 2 && p.Args[1] == "NOT_AVAILABLE") {
  1126. continue;
  1127. }
  1128. Json::Value testInfo = DumpCTestInfo(testRun, p, backtraceGraph);
  1129. tests.append(testInfo);
  1130. }
  1131. result["backtraceGraph"] = backtraceGraph.Dump();
  1132. result["tests"] = std::move(tests);
  1133. Json::StreamWriterBuilder builder;
  1134. builder["indentation"] = " ";
  1135. std::unique_ptr<Json::StreamWriter> jout(builder.newStreamWriter());
  1136. jout->write(result, &std::cout);
  1137. }
  1138. // For ShowOnly mode
  1139. void cmCTestMultiProcessHandler::PrintTestList()
  1140. {
  1141. if (this->CTest->GetOutputAsJson()) {
  1142. this->PrintOutputAsJson();
  1143. return;
  1144. }
  1145. this->TestHandler->SetMaxIndex(this->FindMaxIndex());
  1146. for (auto& it : this->Properties) {
  1147. cmCTestTestHandler::cmCTestTestProperties& p = *it.second;
  1148. // Don't worry if this fails, we are only showing the test list, not
  1149. // running the tests
  1150. cmWorkingDirectory workdir(p.Directory);
  1151. cmCTestRunTest testRun(*this, p.Index);
  1152. testRun.ComputeArguments(); // logs the command in verbose mode
  1153. if (!p.Labels.empty()) // print the labels
  1154. {
  1155. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  1156. "Labels:", this->Quiet);
  1157. }
  1158. for (std::string const& label : p.Labels) {
  1159. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, " " << label,
  1160. this->Quiet);
  1161. }
  1162. if (!p.Labels.empty()) // print the labels
  1163. {
  1164. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT, std::endl,
  1165. this->Quiet);
  1166. }
  1167. if (this->TestHandler->MemCheck) {
  1168. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, " Memory Check",
  1169. this->Quiet);
  1170. } else {
  1171. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, " Test", this->Quiet);
  1172. }
  1173. std::ostringstream indexStr;
  1174. indexStr << " #" << p.Index << ":";
  1175. cmCTestOptionalLog(
  1176. this->CTest, HANDLER_OUTPUT,
  1177. std::setw(3 + getNumWidth(this->TestHandler->GetMaxIndex()))
  1178. << indexStr.str(),
  1179. this->Quiet);
  1180. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, " " << p.Name,
  1181. this->Quiet);
  1182. if (p.Disabled) {
  1183. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, " (Disabled)",
  1184. this->Quiet);
  1185. }
  1186. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, std::endl, this->Quiet);
  1187. }
  1188. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  1189. std::endl
  1190. << "Total Tests: " << this->Total << std::endl,
  1191. this->Quiet);
  1192. }
  1193. void cmCTestMultiProcessHandler::PrintLabels()
  1194. {
  1195. std::set<std::string> allLabels;
  1196. for (auto& it : this->Properties) {
  1197. cmCTestTestHandler::cmCTestTestProperties& p = *it.second;
  1198. allLabels.insert(p.Labels.begin(), p.Labels.end());
  1199. }
  1200. if (!allLabels.empty()) {
  1201. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, "All Labels:" << std::endl,
  1202. this->Quiet);
  1203. } else {
  1204. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  1205. "No Labels Exist" << std::endl, this->Quiet);
  1206. }
  1207. for (std::string const& label : allLabels) {
  1208. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, " " << label << std::endl,
  1209. this->Quiet);
  1210. }
  1211. }
  1212. void cmCTestMultiProcessHandler::CheckResume()
  1213. {
  1214. std::string fname =
  1215. this->CTest->GetBinaryDir() + "/Testing/Temporary/CTestCheckpoint.txt";
  1216. if (this->CTest->GetFailover()) {
  1217. if (cmSystemTools::FileExists(fname, true)) {
  1218. *this->TestHandler->LogFile
  1219. << "Resuming previously interrupted test set" << std::endl
  1220. << "----------------------------------------------------------"
  1221. << std::endl;
  1222. cmsys::ifstream fin;
  1223. fin.open(fname.c_str());
  1224. std::string line;
  1225. while (std::getline(fin, line)) {
  1226. int index = atoi(line.c_str());
  1227. this->RemoveTest(index);
  1228. }
  1229. fin.close();
  1230. }
  1231. } else if (cmSystemTools::FileExists(fname, true)) {
  1232. cmSystemTools::RemoveFile(fname);
  1233. }
  1234. }
  1235. void cmCTestMultiProcessHandler::RemoveTest(int index)
  1236. {
  1237. this->ErasePendingTest(index);
  1238. this->Properties.erase(index);
  1239. this->Completed++;
  1240. }
  1241. int cmCTestMultiProcessHandler::FindMaxIndex()
  1242. {
  1243. int max = 0;
  1244. for (auto const& i : this->PendingTests) {
  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->PendingTests) {
  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->PendingTests[test].Depends) {
  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. }
  1288. bool cmCTestMultiProcessHandler::CheckGeneratedResourceSpec()
  1289. {
  1290. for (auto& test : this->Properties) {
  1291. if (!test.second->GeneratedResourceSpecFile.empty()) {
  1292. if (this->ResourceSpecSetupTest) {
  1293. cmCTestLog(
  1294. this->CTest, ERROR_MESSAGE,
  1295. "Only one test may define the GENERATED_RESOURCE_SPEC_FILE property"
  1296. << std::endl);
  1297. return false;
  1298. }
  1299. if (test.second->FixturesSetup.size() != 1) {
  1300. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1301. "Test that defines GENERATED_RESOURCE_SPEC_FILE must have "
  1302. "exactly one FIXTURES_SETUP"
  1303. << std::endl);
  1304. return false;
  1305. }
  1306. if (!cmSystemTools::FileIsFullPath(
  1307. test.second->GeneratedResourceSpecFile)) {
  1308. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1309. "GENERATED_RESOURCE_SPEC_FILE must be an absolute path"
  1310. << std::endl);
  1311. return false;
  1312. }
  1313. this->ResourceSpecSetupTest = test.first;
  1314. this->ResourceSpecSetupFixture = *test.second->FixturesSetup.begin();
  1315. }
  1316. }
  1317. if (!this->ResourceSpecSetupFixture.empty()) {
  1318. for (auto& test : this->Properties) {
  1319. if (!test.second->ResourceGroups.empty() &&
  1320. !test.second->FixturesRequired.count(
  1321. this->ResourceSpecSetupFixture)) {
  1322. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1323. "All tests that have RESOURCE_GROUPS must include the "
  1324. "resource spec generator fixture in their FIXTURES_REQUIRED"
  1325. << std::endl);
  1326. return false;
  1327. }
  1328. }
  1329. }
  1330. if (!this->ResourceSpecFile.empty()) {
  1331. if (this->ResourceSpecSetupTest) {
  1332. cmCTestLog(this->CTest, ERROR_MESSAGE,
  1333. "GENERATED_RESOURCE_SPEC_FILE test property cannot be used "
  1334. "in conjunction with ResourceSpecFile option"
  1335. << std::endl);
  1336. return false;
  1337. }
  1338. std::string error;
  1339. if (!this->InitResourceAllocator(error)) {
  1340. cmCTestLog(this->CTest, ERROR_MESSAGE, error << std::endl);
  1341. return false;
  1342. }
  1343. }
  1344. return true;
  1345. }
  1346. bool cmCTestMultiProcessHandler::InitResourceAllocator(std::string& error)
  1347. {
  1348. if (!this->ResourceSpec.ReadFromJSONFile(this->ResourceSpecFile)) {
  1349. error = cmStrCat("Could not read/parse resource spec file ",
  1350. this->ResourceSpecFile, ": ",
  1351. this->ResourceSpec.parseState.GetErrorMessage());
  1352. return false;
  1353. }
  1354. this->UseResourceSpec = true;
  1355. this->ResourceAllocator.InitializeFromResourceSpec(this->ResourceSpec);
  1356. return true;
  1357. }