cmCTestMultiProcessHandler.cxx 45 KB

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