cmInstrumentation.cxx 24 KB

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