cmInstrumentation.cxx 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745
  1. #include "cmInstrumentation.h"
  2. #include <chrono>
  3. #include <ctime>
  4. #include <iomanip>
  5. #include <memory>
  6. #include <set>
  7. #include <sstream>
  8. #include <utility>
  9. #include <cm/optional>
  10. #include <cm3p/json/writer.h>
  11. #include <cm3p/uv.h>
  12. #include "cmsys/Directory.hxx"
  13. #include "cmsys/FStream.hxx"
  14. #include <cmsys/SystemInformation.hxx>
  15. #include "cmCryptoHash.h"
  16. #include "cmExperimental.h"
  17. #include "cmInstrumentationQuery.h"
  18. #include "cmJSONState.h"
  19. #include "cmStringAlgorithms.h"
  20. #include "cmSystemTools.h"
  21. #include "cmTimestamp.h"
  22. #include "cmUVProcessChain.h"
  23. #include "cmValue.h"
  24. cmInstrumentation::cmInstrumentation(std::string const& binary_dir)
  25. {
  26. std::string const uuid =
  27. cmExperimental::DataForFeature(cmExperimental::Feature::Instrumentation)
  28. .Uuid;
  29. this->binaryDir = binary_dir;
  30. this->timingDirv1 =
  31. cmStrCat(this->binaryDir, "/.cmake/instrumentation-", uuid, "/v1");
  32. if (cm::optional<std::string> configDir =
  33. cmSystemTools::GetCMakeConfigDirectory()) {
  34. this->userTimingDirv1 =
  35. cmStrCat(configDir.value(), "/instrumentation-", uuid, "/v1");
  36. }
  37. this->LoadQueries();
  38. }
  39. void cmInstrumentation::LoadQueries()
  40. {
  41. if (cmSystemTools::FileExists(cmStrCat(this->timingDirv1, "/query"))) {
  42. this->hasQuery =
  43. this->ReadJSONQueries(cmStrCat(this->timingDirv1, "/query")) ||
  44. this->ReadJSONQueries(cmStrCat(this->timingDirv1, "/query/generated"));
  45. }
  46. if (!this->userTimingDirv1.empty() &&
  47. cmSystemTools::FileExists(cmStrCat(this->userTimingDirv1, "/query"))) {
  48. this->hasQuery = this->hasQuery ||
  49. this->ReadJSONQueries(cmStrCat(this->userTimingDirv1, "/query"));
  50. }
  51. std::string envVal;
  52. if (cmSystemTools::GetEnv("CTEST_USE_INSTRUMENTATION", envVal) &&
  53. !cmIsOff(envVal)) {
  54. if (cmSystemTools::GetEnv("CTEST_EXPERIMENTAL_INSTRUMENTATION", envVal)) {
  55. std::string const uuid = cmExperimental::DataForFeature(
  56. cmExperimental::Feature::Instrumentation)
  57. .Uuid;
  58. if (envVal == uuid) {
  59. this->AddHook(cmInstrumentationQuery::Hook::PrepareForCDash);
  60. this->AddQuery(
  61. cmInstrumentationQuery::Query::DynamicSystemInformation);
  62. this->cdashDir = cmStrCat(this->timingDirv1, "/cdash");
  63. cmSystemTools::MakeDirectory(this->cdashDir);
  64. cmSystemTools::MakeDirectory(cmStrCat(this->cdashDir, "/configure"));
  65. cmSystemTools::MakeDirectory(cmStrCat(this->cdashDir, "/build"));
  66. cmSystemTools::MakeDirectory(
  67. cmStrCat(this->cdashDir, "/build/commands"));
  68. cmSystemTools::MakeDirectory(
  69. cmStrCat(this->cdashDir, "/build/targets"));
  70. cmSystemTools::MakeDirectory(cmStrCat(this->cdashDir, "/test"));
  71. this->cdashSnippetsMap = { {
  72. "configure",
  73. "configure",
  74. },
  75. {
  76. "generate",
  77. "configure",
  78. },
  79. {
  80. "compile",
  81. "build",
  82. },
  83. {
  84. "link",
  85. "build",
  86. },
  87. {
  88. "custom",
  89. "build",
  90. },
  91. {
  92. "build",
  93. "skip",
  94. },
  95. {
  96. "cmakeBuild",
  97. "build",
  98. },
  99. {
  100. "cmakeInstall",
  101. "build",
  102. },
  103. {
  104. "install",
  105. "build",
  106. },
  107. {
  108. "ctest",
  109. "build",
  110. },
  111. {
  112. "test",
  113. "test",
  114. } };
  115. this->hasQuery = true;
  116. }
  117. }
  118. }
  119. }
  120. bool cmInstrumentation::ReadJSONQueries(std::string const& directory)
  121. {
  122. cmsys::Directory d;
  123. std::string json = ".json";
  124. bool result = false;
  125. if (d.Load(directory)) {
  126. for (unsigned int i = 0; i < d.GetNumberOfFiles(); i++) {
  127. std::string fpath = d.GetFilePath(i);
  128. if (fpath.rfind(json) == (fpath.size() - json.size())) {
  129. result = true;
  130. this->ReadJSONQuery(fpath);
  131. }
  132. }
  133. }
  134. return result;
  135. }
  136. void cmInstrumentation::ReadJSONQuery(std::string const& file)
  137. {
  138. auto query = cmInstrumentationQuery();
  139. query.ReadJSON(file, this->errorMsg, this->queries, this->hooks,
  140. this->callbacks);
  141. if (!this->errorMsg.empty()) {
  142. cmSystemTools::Error(cmStrCat(
  143. "Could not load instrumentation queries from ",
  144. cmSystemTools::GetParentDirectory(file), ":\n", this->errorMsg));
  145. }
  146. }
  147. bool cmInstrumentation::HasErrors() const
  148. {
  149. return !this->errorMsg.empty();
  150. }
  151. void cmInstrumentation::WriteJSONQuery(
  152. std::set<cmInstrumentationQuery::Query> const& queries_,
  153. std::set<cmInstrumentationQuery::Hook> const& hooks_,
  154. std::vector<std::vector<std::string>> const& callbacks_)
  155. {
  156. Json::Value root;
  157. root["version"] = 1;
  158. root["queries"] = Json::arrayValue;
  159. for (auto const& query : queries_) {
  160. root["queries"].append(cmInstrumentationQuery::QueryString[query]);
  161. }
  162. root["hooks"] = Json::arrayValue;
  163. for (auto const& hook : hooks_) {
  164. root["hooks"].append(cmInstrumentationQuery::HookString[hook]);
  165. }
  166. root["callbacks"] = Json::arrayValue;
  167. for (auto const& callback : callbacks_) {
  168. root["callbacks"].append(cmInstrumentation::GetCommandStr(callback));
  169. }
  170. cmsys::Directory d;
  171. int n = 0;
  172. if (d.Load(cmStrCat(this->timingDirv1, "/query/generated"))) {
  173. n = (int)d.GetNumberOfFiles() - 2; // Don't count '.' or '..'
  174. }
  175. this->WriteInstrumentationJson(root, "query/generated",
  176. cmStrCat("query-", n, ".json"));
  177. }
  178. void cmInstrumentation::ClearGeneratedQueries()
  179. {
  180. std::string dir = cmStrCat(this->timingDirv1, "/query/generated");
  181. if (cmSystemTools::FileIsDirectory(dir)) {
  182. cmSystemTools::RemoveADirectory(dir);
  183. }
  184. }
  185. bool cmInstrumentation::HasQuery() const
  186. {
  187. return this->hasQuery;
  188. }
  189. bool cmInstrumentation::HasQuery(cmInstrumentationQuery::Query query) const
  190. {
  191. return (this->queries.find(query) != this->queries.end());
  192. }
  193. bool cmInstrumentation::HasHook(cmInstrumentationQuery::Hook hook) const
  194. {
  195. return (this->hooks.find(hook) != this->hooks.end());
  196. }
  197. bool cmInstrumentation::HasPreOrPostBuildHook() const
  198. {
  199. return (this->HasHook(cmInstrumentationQuery::Hook::PreBuild) ||
  200. this->HasHook(cmInstrumentationQuery::Hook::PostBuild));
  201. }
  202. int cmInstrumentation::CollectTimingData(cmInstrumentationQuery::Hook hook)
  203. {
  204. // Don't run collection if hook is disabled
  205. if (hook != cmInstrumentationQuery::Hook::Manual &&
  206. this->hooks.find(hook) == this->hooks.end()) {
  207. return 0;
  208. }
  209. // Touch index file immediately to claim snippets
  210. std::string const& directory = cmStrCat(this->timingDirv1, "/data");
  211. std::string const& file_name =
  212. cmStrCat("index-", ComputeSuffixTime(), ".json");
  213. std::string index_path = cmStrCat(directory, '/', file_name);
  214. cmSystemTools::Touch(index_path, true);
  215. // Gather Snippets
  216. using snippet = std::pair<std::string, std::string>;
  217. std::vector<snippet> files;
  218. cmsys::Directory d;
  219. std::string last_index;
  220. if (d.Load(directory)) {
  221. for (unsigned int i = 0; i < d.GetNumberOfFiles(); i++) {
  222. std::string fpath = d.GetFilePath(i);
  223. std::string fname = d.GetFile(i);
  224. if (fname.rfind('.', 0) == 0) {
  225. continue;
  226. }
  227. if (fname == file_name) {
  228. continue;
  229. }
  230. if (fname.rfind("index-", 0) == 0) {
  231. if (last_index.empty()) {
  232. last_index = fpath;
  233. } else {
  234. int compare;
  235. cmSystemTools::FileTimeCompare(fpath, last_index, &compare);
  236. if (compare == 1) {
  237. last_index = fpath;
  238. }
  239. }
  240. }
  241. files.push_back(snippet(std::move(fname), std::move(fpath)));
  242. }
  243. }
  244. // Build Json Object
  245. Json::Value index(Json::objectValue);
  246. index["snippets"] = Json::arrayValue;
  247. index["hook"] = cmInstrumentationQuery::HookString[hook];
  248. index["dataDir"] = directory;
  249. index["buildDir"] = this->binaryDir;
  250. index["version"] = 1;
  251. if (this->HasQuery(cmInstrumentationQuery::Query::StaticSystemInformation)) {
  252. this->InsertStaticSystemInformation(index);
  253. }
  254. for (auto const& file : files) {
  255. if (last_index.empty()) {
  256. index["snippets"].append(file.first);
  257. } else {
  258. int compare;
  259. cmSystemTools::FileTimeCompare(file.second, last_index, &compare);
  260. if (compare == 1) {
  261. index["snippets"].append(file.first);
  262. }
  263. }
  264. }
  265. this->WriteInstrumentationJson(index, "data", file_name);
  266. // Execute callbacks
  267. for (auto& cb : this->callbacks) {
  268. cmSystemTools::RunSingleCommand(cmStrCat(cb, " \"", index_path, '"'),
  269. nullptr, nullptr, nullptr, nullptr,
  270. cmSystemTools::OUTPUT_PASSTHROUGH);
  271. }
  272. // Special case for CDash collation
  273. if (this->HasHook(cmInstrumentationQuery::Hook::PrepareForCDash)) {
  274. this->PrepareDataForCDash(directory, index_path);
  275. }
  276. // Delete files
  277. for (auto const& f : index["snippets"]) {
  278. cmSystemTools::RemoveFile(cmStrCat(directory, '/', f.asString()));
  279. }
  280. cmSystemTools::RemoveFile(index_path);
  281. return 0;
  282. }
  283. void cmInstrumentation::InsertDynamicSystemInformation(
  284. Json::Value& root, std::string const& prefix)
  285. {
  286. cmsys::SystemInformation info;
  287. Json::Value data;
  288. info.RunCPUCheck();
  289. info.RunMemoryCheck();
  290. if (!root.isMember("dynamicSystemInformation")) {
  291. root["dynamicSystemInformation"] = Json::objectValue;
  292. }
  293. root["dynamicSystemInformation"][cmStrCat(prefix, "HostMemoryUsed")] =
  294. (double)info.GetHostMemoryUsed();
  295. root["dynamicSystemInformation"][cmStrCat(prefix, "CPULoadAverage")] =
  296. info.GetLoadAverage();
  297. }
  298. void cmInstrumentation::GetDynamicSystemInformation(double& memory,
  299. double& load)
  300. {
  301. cmsys::SystemInformation info;
  302. Json::Value data;
  303. info.RunCPUCheck();
  304. info.RunMemoryCheck();
  305. memory = (double)info.GetHostMemoryUsed();
  306. load = info.GetLoadAverage();
  307. }
  308. void cmInstrumentation::InsertStaticSystemInformation(Json::Value& root)
  309. {
  310. cmsys::SystemInformation info;
  311. info.RunCPUCheck();
  312. info.RunOSCheck();
  313. info.RunMemoryCheck();
  314. Json::Value infoRoot;
  315. infoRoot["familyId"] = info.GetFamilyID();
  316. infoRoot["hostname"] = info.GetHostname();
  317. infoRoot["is64Bits"] = info.Is64Bits();
  318. infoRoot["modelId"] = info.GetModelID();
  319. infoRoot["numberOfLogicalCPU"] = info.GetNumberOfLogicalCPU();
  320. infoRoot["numberOfPhysicalCPU"] = info.GetNumberOfPhysicalCPU();
  321. infoRoot["OSName"] = info.GetOSName();
  322. infoRoot["OSPlatform"] = info.GetOSPlatform();
  323. infoRoot["OSRelease"] = info.GetOSRelease();
  324. infoRoot["OSVersion"] = info.GetOSVersion();
  325. infoRoot["processorAPICID"] = info.GetProcessorAPICID();
  326. infoRoot["processorCacheSize"] = info.GetProcessorCacheSize();
  327. infoRoot["processorClockFrequency"] =
  328. (double)info.GetProcessorClockFrequency();
  329. infoRoot["processorName"] = info.GetExtendedProcessorName();
  330. infoRoot["totalPhysicalMemory"] =
  331. static_cast<Json::Value::UInt64>(info.GetTotalPhysicalMemory());
  332. infoRoot["totalVirtualMemory"] =
  333. static_cast<Json::Value::UInt64>(info.GetTotalVirtualMemory());
  334. infoRoot["vendorID"] = info.GetVendorID();
  335. infoRoot["vendorString"] = info.GetVendorString();
  336. root["staticSystemInformation"] = infoRoot;
  337. }
  338. void cmInstrumentation::InsertTimingData(
  339. Json::Value& root, std::chrono::steady_clock::time_point steadyStart,
  340. std::chrono::system_clock::time_point systemStart)
  341. {
  342. uint64_t timeStart = std::chrono::duration_cast<std::chrono::milliseconds>(
  343. systemStart.time_since_epoch())
  344. .count();
  345. uint64_t duration = std::chrono::duration_cast<std::chrono::milliseconds>(
  346. std::chrono::steady_clock::now() - steadyStart)
  347. .count();
  348. root["timeStart"] = static_cast<Json::Value::UInt64>(timeStart);
  349. root["duration"] = static_cast<Json::Value::UInt64>(duration);
  350. }
  351. void cmInstrumentation::WriteInstrumentationJson(Json::Value& root,
  352. std::string const& subdir,
  353. std::string const& file_name)
  354. {
  355. Json::StreamWriterBuilder wbuilder;
  356. wbuilder["indentation"] = "\t";
  357. std::unique_ptr<Json::StreamWriter> JsonWriter =
  358. std::unique_ptr<Json::StreamWriter>(wbuilder.newStreamWriter());
  359. std::string const& directory = cmStrCat(this->timingDirv1, '/', subdir);
  360. cmSystemTools::MakeDirectory(directory);
  361. cmsys::ofstream ftmp(cmStrCat(directory, '/', file_name).c_str());
  362. JsonWriter->write(root, &ftmp);
  363. ftmp << "\n";
  364. ftmp.close();
  365. }
  366. std::string cmInstrumentation::InstrumentTest(
  367. std::string const& name, std::string const& command,
  368. std::vector<std::string> const& args, int64_t result,
  369. std::chrono::steady_clock::time_point steadyStart,
  370. std::chrono::system_clock::time_point systemStart, std::string config)
  371. {
  372. // Store command info
  373. Json::Value root(this->preTestStats);
  374. std::string command_str = cmStrCat(command, ' ', GetCommandStr(args));
  375. root["version"] = 1;
  376. root["command"] = command_str;
  377. root["role"] = "test";
  378. root["testName"] = name;
  379. root["result"] = static_cast<Json::Value::Int64>(result);
  380. root["config"] = config;
  381. root["workingDir"] = cmSystemTools::GetLogicalWorkingDirectory();
  382. // Post-Command
  383. this->InsertTimingData(root, steadyStart, systemStart);
  384. if (this->HasQuery(
  385. cmInstrumentationQuery::Query::DynamicSystemInformation)) {
  386. this->InsertDynamicSystemInformation(root, "after");
  387. }
  388. cmsys::SystemInformation info;
  389. std::string file_name = cmStrCat(
  390. "test-",
  391. this->ComputeSuffixHash(cmStrCat(command_str, info.GetProcessId())),
  392. this->ComputeSuffixTime(), ".json");
  393. this->WriteInstrumentationJson(root, "data", file_name);
  394. return file_name;
  395. }
  396. void cmInstrumentation::GetPreTestStats()
  397. {
  398. if (this->HasQuery(
  399. cmInstrumentationQuery::Query::DynamicSystemInformation)) {
  400. this->InsertDynamicSystemInformation(this->preTestStats, "before");
  401. }
  402. }
  403. int cmInstrumentation::InstrumentCommand(
  404. std::string command_type, std::vector<std::string> const& command,
  405. std::function<int()> const& callback,
  406. cm::optional<std::map<std::string, std::string>> options,
  407. cm::optional<std::map<std::string, std::string>> arrayOptions,
  408. bool reloadQueriesAfterCommand)
  409. {
  410. // Always begin gathering data for configure in case cmake_instrumentation
  411. // command creates a query
  412. if (!this->hasQuery && !reloadQueriesAfterCommand) {
  413. return callback();
  414. }
  415. // Store command info
  416. Json::Value root(Json::objectValue);
  417. Json::Value commandInfo(Json::objectValue);
  418. std::string command_str = GetCommandStr(command);
  419. if (!command_str.empty()) {
  420. root["command"] = command_str;
  421. }
  422. root["version"] = 1;
  423. // Pre-Command
  424. auto steady_start = std::chrono::steady_clock::now();
  425. auto system_start = std::chrono::system_clock::now();
  426. double preConfigureMemory = 0;
  427. double preConfigureLoad = 0;
  428. if (this->HasQuery(
  429. cmInstrumentationQuery::Query::DynamicSystemInformation)) {
  430. this->InsertDynamicSystemInformation(root, "before");
  431. } else if (reloadQueriesAfterCommand) {
  432. this->GetDynamicSystemInformation(preConfigureMemory, preConfigureLoad);
  433. }
  434. // Execute Command
  435. int ret = callback();
  436. root["result"] = ret;
  437. // Exit early if configure didn't generate a query
  438. if (reloadQueriesAfterCommand) {
  439. this->LoadQueries();
  440. if (!this->hasQuery) {
  441. return ret;
  442. }
  443. if (this->HasQuery(
  444. cmInstrumentationQuery::Query::DynamicSystemInformation)) {
  445. root["dynamicSystemInformation"] = Json::objectValue;
  446. root["dynamicSystemInformation"]["beforeHostMemoryUsed"] =
  447. preConfigureMemory;
  448. root["dynamicSystemInformation"]["beforeCPULoadAverage"] =
  449. preConfigureLoad;
  450. }
  451. }
  452. // Post-Command
  453. this->InsertTimingData(root, steady_start, system_start);
  454. if (this->HasQuery(
  455. cmInstrumentationQuery::Query::DynamicSystemInformation)) {
  456. this->InsertDynamicSystemInformation(root, "after");
  457. }
  458. // Gather additional data
  459. if (options.has_value()) {
  460. for (auto const& item : options.value()) {
  461. if (item.first == "role" && !item.second.empty()) {
  462. command_type = item.second;
  463. } else if (!item.second.empty()) {
  464. root[item.first] = item.second;
  465. }
  466. }
  467. }
  468. // Create empty config entry if config not found
  469. if (!root.isMember("config") &&
  470. (command_type == "compile" || command_type == "link")) {
  471. root["config"] = "";
  472. }
  473. if (arrayOptions.has_value()) {
  474. for (auto const& item : arrayOptions.value()) {
  475. if (item.first == "targetLabels" && command_type != "link") {
  476. continue;
  477. }
  478. root[item.first] = Json::arrayValue;
  479. std::stringstream ss(item.second);
  480. std::string element;
  481. while (getline(ss, element, ',')) {
  482. root[item.first].append(element);
  483. }
  484. if (item.first == "outputs") {
  485. root["outputSizes"] = Json::arrayValue;
  486. for (auto const& output : root["outputs"]) {
  487. root["outputSizes"].append(
  488. static_cast<Json::Value::UInt64>(cmSystemTools::FileLength(
  489. cmStrCat(this->binaryDir, '/', output.asCString()))));
  490. }
  491. }
  492. }
  493. }
  494. root["role"] = command_type;
  495. root["workingDir"] = cmSystemTools::GetLogicalWorkingDirectory();
  496. // Write Json
  497. cmsys::SystemInformation info;
  498. std::string const& file_name = cmStrCat(
  499. command_type, '-',
  500. this->ComputeSuffixHash(cmStrCat(command_str, info.GetProcessId())),
  501. this->ComputeSuffixTime(), ".json");
  502. this->WriteInstrumentationJson(root, "data", file_name);
  503. return ret;
  504. }
  505. std::string cmInstrumentation::GetCommandStr(
  506. std::vector<std::string> const& args)
  507. {
  508. std::string command_str;
  509. for (size_t i = 0; i < args.size(); ++i) {
  510. command_str = cmStrCat(command_str, '"', args[i], '"');
  511. if (i < args.size() - 1) {
  512. command_str = cmStrCat(command_str, ' ');
  513. }
  514. }
  515. return command_str;
  516. }
  517. std::string cmInstrumentation::ComputeSuffixHash(
  518. std::string const& command_str)
  519. {
  520. cmCryptoHash hasher(cmCryptoHash::AlgoSHA3_256);
  521. std::string hash = hasher.HashString(command_str);
  522. hash.resize(20, '0');
  523. return hash;
  524. }
  525. std::string cmInstrumentation::ComputeSuffixTime()
  526. {
  527. std::chrono::milliseconds ms =
  528. std::chrono::duration_cast<std::chrono::milliseconds>(
  529. std::chrono::system_clock::now().time_since_epoch());
  530. std::chrono::seconds s =
  531. std::chrono::duration_cast<std::chrono::seconds>(ms);
  532. std::time_t ts = s.count();
  533. std::size_t tms = ms.count() % 1000;
  534. cmTimestamp cmts;
  535. std::ostringstream ss;
  536. ss << cmts.CreateTimestampFromTimeT(ts, "%Y-%m-%dT%H-%M-%S", true) << '-'
  537. << std::setfill('0') << std::setw(4) << tms;
  538. return ss.str();
  539. }
  540. /*
  541. * Called by ctest --start-instrumentation as part of the START_INSTRUMENTATION
  542. * rule when using the Ninja generator.
  543. * This creates a detached process which waits for the Ninja process to die
  544. * before running the postBuild hook. In this way, the postBuild hook triggers
  545. * after every ninja invocation, regardless of whether the build passed or
  546. * failed.
  547. */
  548. int cmInstrumentation::SpawnBuildDaemon()
  549. {
  550. // preBuild Hook
  551. this->CollectTimingData(cmInstrumentationQuery::Hook::PreBuild);
  552. // postBuild Hook
  553. if (this->HasHook(cmInstrumentationQuery::Hook::PostBuild)) {
  554. auto ninja_pid = uv_os_getppid();
  555. if (ninja_pid) {
  556. std::vector<std::string> args;
  557. args.push_back(cmSystemTools::GetCTestCommand());
  558. args.push_back("--wait-and-collect-instrumentation");
  559. args.push_back(this->binaryDir);
  560. args.push_back(std::to_string(ninja_pid));
  561. auto builder = cmUVProcessChainBuilder().SetDetached().AddCommand(args);
  562. auto chain = builder.Start();
  563. uv_run(&chain.GetLoop(), UV_RUN_DEFAULT);
  564. }
  565. }
  566. return 0;
  567. }
  568. /*
  569. * Always called by ctest --wait-and-collect-instrumentation in a detached
  570. * process. Waits for the given PID to end before running the postBuild hook.
  571. *
  572. * See SpawnBuildDaemon()
  573. */
  574. int cmInstrumentation::CollectTimingAfterBuild(int ppid)
  575. {
  576. std::function<int()> waitForBuild = [ppid]() -> int {
  577. while (0 == uv_kill(ppid, 0)) {
  578. cmSystemTools::Delay(100);
  579. };
  580. return 0;
  581. };
  582. int ret = this->InstrumentCommand(
  583. "build", {}, [waitForBuild]() { return waitForBuild(); }, cm::nullopt,
  584. cm::nullopt, false);
  585. this->CollectTimingData(cmInstrumentationQuery::Hook::PostBuild);
  586. return ret;
  587. }
  588. void cmInstrumentation::AddHook(cmInstrumentationQuery::Hook hook)
  589. {
  590. this->hooks.insert(hook);
  591. }
  592. void cmInstrumentation::AddQuery(cmInstrumentationQuery::Query query)
  593. {
  594. this->queries.insert(query);
  595. }
  596. std::string const& cmInstrumentation::GetCDashDir()
  597. {
  598. return this->cdashDir;
  599. }
  600. /** Copy the snippets referred to by an index file to a separate
  601. * directory where they will be parsed for submission to CDash.
  602. **/
  603. void cmInstrumentation::PrepareDataForCDash(std::string const& data_dir,
  604. std::string const& index_path)
  605. {
  606. Json::Value root;
  607. std::string error_msg;
  608. cmJSONState parseState = cmJSONState(index_path, &root);
  609. if (!parseState.errors.empty()) {
  610. cmSystemTools::Error(parseState.GetErrorMessage(true));
  611. return;
  612. }
  613. if (!root.isObject()) {
  614. error_msg =
  615. cmStrCat("Expected index file ", index_path, " to contain an object");
  616. cmSystemTools::Error(error_msg);
  617. return;
  618. }
  619. if (!root.isMember("snippets")) {
  620. error_msg = cmStrCat("Expected index file ", index_path,
  621. " to have a key 'snippets'");
  622. cmSystemTools::Error(error_msg);
  623. return;
  624. }
  625. std::string dst_dir;
  626. Json::Value snippets = root["snippets"];
  627. for (auto const& snippet : snippets) {
  628. // Parse the role of this snippet.
  629. std::string snippet_str = snippet.asString();
  630. std::string snippet_path = cmStrCat(data_dir, '/', snippet_str);
  631. Json::Value snippet_root;
  632. parseState = cmJSONState(snippet_path, &snippet_root);
  633. if (!parseState.errors.empty()) {
  634. cmSystemTools::Error(parseState.GetErrorMessage(true));
  635. continue;
  636. }
  637. if (!snippet_root.isObject()) {
  638. error_msg = cmStrCat("Expected snippet file ", snippet_path,
  639. " to contain an object");
  640. cmSystemTools::Error(error_msg);
  641. continue;
  642. }
  643. if (!snippet_root.isMember("role")) {
  644. error_msg = cmStrCat("Expected snippet file ", snippet_path,
  645. " to have a key 'role'");
  646. cmSystemTools::Error(error_msg);
  647. continue;
  648. }
  649. std::string snippet_role = snippet_root["role"].asString();
  650. auto map_element = this->cdashSnippetsMap.find(snippet_role);
  651. if (map_element == this->cdashSnippetsMap.end()) {
  652. std::string message =
  653. "Unexpected snippet type encountered: " + snippet_role;
  654. cmSystemTools::Message(message, "Warning");
  655. continue;
  656. }
  657. if (map_element->second == "skip") {
  658. continue;
  659. }
  660. if (map_element->second == "build") {
  661. // We organize snippets on a per-target basis (when possible)
  662. // for Build.xml.
  663. if (snippet_root.isMember("target")) {
  664. dst_dir = cmStrCat(this->cdashDir, "/build/targets/",
  665. snippet_root["target"].asString());
  666. cmSystemTools::MakeDirectory(dst_dir);
  667. } else {
  668. dst_dir = cmStrCat(this->cdashDir, "/build/commands");
  669. }
  670. } else {
  671. dst_dir = cmStrCat(this->cdashDir, '/', map_element->second);
  672. }
  673. std::string dst = cmStrCat(dst_dir, '/', snippet_str);
  674. cmsys::Status copied = cmSystemTools::CopyFileAlways(snippet_path, dst);
  675. if (!copied) {
  676. error_msg = cmStrCat("Failed to copy ", snippet_path, " to ", dst);
  677. cmSystemTools::Error(error_msg);
  678. }
  679. }
  680. }