cmCTestMultiProcessHandler.cxx 49 KB

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