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