1
0

cmCTestMultiProcessHandler.cxx 46 KB

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