cmCTestMultiProcessHandler.cxx 50 KB

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