cmInstrumentation.cxx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  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 "cmStringAlgorithms.h"
  19. #include "cmSystemTools.h"
  20. #include "cmTimestamp.h"
  21. #include "cmUVProcessChain.h"
  22. cmInstrumentation::cmInstrumentation(std::string const& binary_dir)
  23. {
  24. std::string const uuid =
  25. cmExperimental::DataForFeature(cmExperimental::Feature::Instrumentation)
  26. .Uuid;
  27. this->binaryDir = binary_dir;
  28. this->timingDirv1 =
  29. cmStrCat(this->binaryDir, "/.cmake/instrumentation-", uuid, "/v1");
  30. if (cm::optional<std::string> configDir =
  31. cmSystemTools::GetCMakeConfigDirectory()) {
  32. this->userTimingDirv1 =
  33. cmStrCat(configDir.value(), "/instrumentation-", uuid, "/v1");
  34. }
  35. this->LoadQueries();
  36. }
  37. void cmInstrumentation::LoadQueries()
  38. {
  39. if (cmSystemTools::FileExists(cmStrCat(this->timingDirv1, "/query"))) {
  40. this->hasQuery =
  41. this->ReadJSONQueries(cmStrCat(this->timingDirv1, "/query")) ||
  42. this->ReadJSONQueries(cmStrCat(this->timingDirv1, "/query/generated"));
  43. }
  44. if (!this->userTimingDirv1.empty() &&
  45. cmSystemTools::FileExists(cmStrCat(this->userTimingDirv1, "/query"))) {
  46. this->hasQuery = this->hasQuery ||
  47. this->ReadJSONQueries(cmStrCat(this->userTimingDirv1, "/query"));
  48. }
  49. }
  50. bool cmInstrumentation::ReadJSONQueries(std::string const& directory)
  51. {
  52. cmsys::Directory d;
  53. std::string json = ".json";
  54. bool result = false;
  55. if (d.Load(directory)) {
  56. for (unsigned int i = 0; i < d.GetNumberOfFiles(); i++) {
  57. std::string fpath = d.GetFilePath(i);
  58. if (fpath.rfind(json) == (fpath.size() - json.size())) {
  59. result = true;
  60. this->ReadJSONQuery(fpath);
  61. }
  62. }
  63. }
  64. return result;
  65. }
  66. void cmInstrumentation::ReadJSONQuery(std::string const& file)
  67. {
  68. auto query = cmInstrumentationQuery();
  69. query.ReadJSON(file, this->errorMsg, this->queries, this->hooks,
  70. this->callbacks);
  71. }
  72. void cmInstrumentation::WriteJSONQuery(
  73. std::set<cmInstrumentationQuery::Query> const& queries_,
  74. std::set<cmInstrumentationQuery::Hook> const& hooks_,
  75. std::vector<std::vector<std::string>> const& callbacks_)
  76. {
  77. Json::Value root;
  78. root["version"] = 1;
  79. root["queries"] = Json::arrayValue;
  80. for (auto const& query : queries_) {
  81. root["queries"].append(cmInstrumentationQuery::QueryString[query]);
  82. }
  83. root["hooks"] = Json::arrayValue;
  84. for (auto const& hook : hooks_) {
  85. root["hooks"].append(cmInstrumentationQuery::HookString[hook]);
  86. }
  87. root["callbacks"] = Json::arrayValue;
  88. for (auto const& callback : callbacks_) {
  89. root["callbacks"].append(cmInstrumentation::GetCommandStr(callback));
  90. }
  91. cmsys::Directory d;
  92. int n = 0;
  93. if (d.Load(cmStrCat(this->timingDirv1, "/query/generated"))) {
  94. n = (int)d.GetNumberOfFiles() - 2; // Don't count '.' or '..'
  95. }
  96. this->WriteInstrumentationJson(root, "query/generated",
  97. cmStrCat("query-", n, ".json"));
  98. }
  99. void cmInstrumentation::ClearGeneratedQueries()
  100. {
  101. std::string dir = cmStrCat(this->timingDirv1, "/query/generated");
  102. if (cmSystemTools::FileIsDirectory(dir)) {
  103. cmSystemTools::RemoveADirectory(dir);
  104. }
  105. }
  106. bool cmInstrumentation::HasQuery() const
  107. {
  108. return this->hasQuery;
  109. }
  110. bool cmInstrumentation::HasQuery(cmInstrumentationQuery::Query query) const
  111. {
  112. return (this->queries.find(query) != this->queries.end());
  113. }
  114. bool cmInstrumentation::HasHook(cmInstrumentationQuery::Hook hook) const
  115. {
  116. return (this->hooks.find(hook) != this->hooks.end());
  117. }
  118. bool cmInstrumentation::HasPreOrPostBuildHook() const
  119. {
  120. return (this->HasHook(cmInstrumentationQuery::Hook::PreBuild) ||
  121. this->HasHook(cmInstrumentationQuery::Hook::PostBuild));
  122. }
  123. int cmInstrumentation::CollectTimingData(cmInstrumentationQuery::Hook hook)
  124. {
  125. // Don't run collection if hook is disabled
  126. if (hook != cmInstrumentationQuery::Hook::Manual &&
  127. this->hooks.find(hook) == this->hooks.end()) {
  128. return 0;
  129. }
  130. // Touch index file immediately to claim snippets
  131. std::string const& directory = cmStrCat(this->timingDirv1, "/data");
  132. std::string const& file_name =
  133. cmStrCat("index-", ComputeSuffixTime(), ".json");
  134. std::string index_path = cmStrCat(directory, "/", file_name);
  135. cmSystemTools::Touch(index_path, true);
  136. // Gather Snippets
  137. using snippet = std::pair<std::string, std::string>;
  138. std::vector<snippet> files;
  139. cmsys::Directory d;
  140. std::string last_index;
  141. if (d.Load(directory)) {
  142. for (unsigned int i = 0; i < d.GetNumberOfFiles(); i++) {
  143. std::string fpath = d.GetFilePath(i);
  144. std::string fname = d.GetFile(i);
  145. if (fname.rfind('.', 0) == 0) {
  146. continue;
  147. }
  148. if (fname == file_name) {
  149. continue;
  150. }
  151. if (fname.rfind("index-", 0) == 0) {
  152. if (last_index.empty()) {
  153. last_index = fpath;
  154. } else {
  155. int compare;
  156. cmSystemTools::FileTimeCompare(fpath, last_index, &compare);
  157. if (compare == 1) {
  158. last_index = fpath;
  159. }
  160. }
  161. }
  162. files.push_back(snippet(std::move(fname), std::move(fpath)));
  163. }
  164. }
  165. // Build Json Object
  166. Json::Value index(Json::objectValue);
  167. index["snippets"] = Json::arrayValue;
  168. index["hook"] = cmInstrumentationQuery::HookString[hook];
  169. index["dataDir"] = directory;
  170. index["buildDir"] = this->binaryDir;
  171. index["version"] = 1;
  172. if (this->HasQuery(cmInstrumentationQuery::Query::StaticSystemInformation)) {
  173. this->InsertStaticSystemInformation(index);
  174. }
  175. for (auto const& file : files) {
  176. if (last_index.empty()) {
  177. index["snippets"].append(file.first);
  178. } else {
  179. int compare;
  180. cmSystemTools::FileTimeCompare(file.second, last_index, &compare);
  181. if (compare == 1) {
  182. index["snippets"].append(file.first);
  183. }
  184. }
  185. }
  186. this->WriteInstrumentationJson(index, "data", file_name);
  187. // Execute callbacks
  188. for (auto& cb : this->callbacks) {
  189. cmSystemTools::RunSingleCommand(cmStrCat(cb, " \"", index_path, "\""),
  190. nullptr, nullptr, nullptr, nullptr,
  191. cmSystemTools::OUTPUT_PASSTHROUGH);
  192. }
  193. // Delete files
  194. for (auto const& f : index["snippets"]) {
  195. cmSystemTools::RemoveFile(cmStrCat(directory, "/", f.asString()));
  196. }
  197. cmSystemTools::RemoveFile(index_path);
  198. return 0;
  199. }
  200. void cmInstrumentation::InsertDynamicSystemInformation(
  201. Json::Value& root, std::string const& prefix)
  202. {
  203. cmsys::SystemInformation info;
  204. Json::Value data;
  205. info.RunCPUCheck();
  206. info.RunMemoryCheck();
  207. if (!root.isMember("dynamicSystemInformation")) {
  208. root["dynamicSystemInformation"] = Json::objectValue;
  209. }
  210. root["dynamicSystemInformation"][cmStrCat(prefix, "HostMemoryUsed")] =
  211. (double)info.GetHostMemoryUsed();
  212. root["dynamicSystemInformation"][cmStrCat(prefix, "CPULoadAverage")] =
  213. info.GetLoadAverage();
  214. }
  215. void cmInstrumentation::GetDynamicSystemInformation(double& memory,
  216. double& load)
  217. {
  218. cmsys::SystemInformation info;
  219. Json::Value data;
  220. info.RunCPUCheck();
  221. info.RunMemoryCheck();
  222. memory = (double)info.GetHostMemoryUsed();
  223. load = info.GetLoadAverage();
  224. }
  225. void cmInstrumentation::InsertStaticSystemInformation(Json::Value& root)
  226. {
  227. cmsys::SystemInformation info;
  228. info.RunCPUCheck();
  229. info.RunOSCheck();
  230. info.RunMemoryCheck();
  231. Json::Value infoRoot;
  232. infoRoot["familyId"] = info.GetFamilyID();
  233. infoRoot["hostname"] = info.GetHostname();
  234. infoRoot["is64Bits"] = info.Is64Bits();
  235. infoRoot["modelId"] = info.GetModelID();
  236. infoRoot["numberOfLogicalCPU"] = info.GetNumberOfLogicalCPU();
  237. infoRoot["numberOfPhysicalCPU"] = info.GetNumberOfPhysicalCPU();
  238. infoRoot["OSName"] = info.GetOSName();
  239. infoRoot["OSPlatform"] = info.GetOSPlatform();
  240. infoRoot["OSRelease"] = info.GetOSRelease();
  241. infoRoot["OSVersion"] = info.GetOSVersion();
  242. infoRoot["processorAPICID"] = info.GetProcessorAPICID();
  243. infoRoot["processorCacheSize"] = info.GetProcessorCacheSize();
  244. infoRoot["processorClockFrequency"] =
  245. (double)info.GetProcessorClockFrequency();
  246. infoRoot["processorName"] = info.GetExtendedProcessorName();
  247. infoRoot["totalPhysicalMemory"] =
  248. static_cast<Json::Value::UInt64>(info.GetTotalPhysicalMemory());
  249. infoRoot["totalVirtualMemory"] =
  250. static_cast<Json::Value::UInt64>(info.GetTotalVirtualMemory());
  251. infoRoot["vendorID"] = info.GetVendorID();
  252. infoRoot["vendorString"] = info.GetVendorString();
  253. root["staticSystemInformation"] = infoRoot;
  254. }
  255. void cmInstrumentation::InsertTimingData(
  256. Json::Value& root, std::chrono::steady_clock::time_point steadyStart,
  257. std::chrono::system_clock::time_point systemStart)
  258. {
  259. uint64_t timeStart = std::chrono::duration_cast<std::chrono::milliseconds>(
  260. systemStart.time_since_epoch())
  261. .count();
  262. uint64_t duration = std::chrono::duration_cast<std::chrono::milliseconds>(
  263. std::chrono::steady_clock::now() - steadyStart)
  264. .count();
  265. root["timeStart"] = static_cast<Json::Value::UInt64>(timeStart);
  266. root["duration"] = static_cast<Json::Value::UInt64>(duration);
  267. }
  268. void cmInstrumentation::WriteInstrumentationJson(Json::Value& root,
  269. std::string const& subdir,
  270. std::string const& file_name)
  271. {
  272. Json::StreamWriterBuilder wbuilder;
  273. wbuilder["indentation"] = "\t";
  274. std::unique_ptr<Json::StreamWriter> JsonWriter =
  275. std::unique_ptr<Json::StreamWriter>(wbuilder.newStreamWriter());
  276. std::string const& directory = cmStrCat(this->timingDirv1, "/", subdir);
  277. cmSystemTools::MakeDirectory(directory);
  278. cmsys::ofstream ftmp(cmStrCat(directory, "/", file_name).c_str());
  279. JsonWriter->write(root, &ftmp);
  280. ftmp << "\n";
  281. ftmp.close();
  282. }
  283. int cmInstrumentation::InstrumentTest(
  284. std::string const& name, std::string const& command,
  285. std::vector<std::string> const& args, int64_t result,
  286. std::chrono::steady_clock::time_point steadyStart,
  287. std::chrono::system_clock::time_point systemStart)
  288. {
  289. // Store command info
  290. Json::Value root(this->preTestStats);
  291. std::string command_str = cmStrCat(command, ' ', GetCommandStr(args));
  292. root["version"] = 1;
  293. root["command"] = command_str;
  294. root["role"] = "test";
  295. root["testName"] = name;
  296. root["binaryDir"] = this->binaryDir;
  297. root["result"] = static_cast<Json::Value::Int64>(result);
  298. // Post-Command
  299. this->InsertTimingData(root, steadyStart, systemStart);
  300. if (this->HasQuery(
  301. cmInstrumentationQuery::Query::DynamicSystemInformation)) {
  302. this->InsertDynamicSystemInformation(root, "after");
  303. }
  304. std::string const& file_name =
  305. cmStrCat("test-", this->ComputeSuffixHash(command_str),
  306. this->ComputeSuffixTime(), ".json");
  307. this->WriteInstrumentationJson(root, "data", file_name);
  308. return 1;
  309. }
  310. void cmInstrumentation::GetPreTestStats()
  311. {
  312. if (this->HasQuery(
  313. cmInstrumentationQuery::Query::DynamicSystemInformation)) {
  314. this->InsertDynamicSystemInformation(this->preTestStats, "before");
  315. }
  316. }
  317. int cmInstrumentation::InstrumentCommand(
  318. std::string command_type, std::vector<std::string> const& command,
  319. std::function<int()> const& callback,
  320. cm::optional<std::map<std::string, std::string>> options,
  321. cm::optional<std::map<std::string, std::string>> arrayOptions,
  322. bool reloadQueriesAfterCommand)
  323. {
  324. // Always begin gathering data for configure in case cmake_instrumentation
  325. // command creates a query
  326. if (!this->hasQuery && !reloadQueriesAfterCommand) {
  327. return callback();
  328. }
  329. // Store command info
  330. Json::Value root(Json::objectValue);
  331. Json::Value commandInfo(Json::objectValue);
  332. std::string command_str = GetCommandStr(command);
  333. root["command"] = command_str;
  334. root["version"] = 1;
  335. // Pre-Command
  336. auto steady_start = std::chrono::steady_clock::now();
  337. auto system_start = std::chrono::system_clock::now();
  338. double preConfigureMemory = 0;
  339. double preConfigureLoad = 0;
  340. if (this->HasQuery(
  341. cmInstrumentationQuery::Query::DynamicSystemInformation)) {
  342. this->InsertDynamicSystemInformation(root, "before");
  343. } else if (reloadQueriesAfterCommand) {
  344. this->GetDynamicSystemInformation(preConfigureMemory, preConfigureLoad);
  345. }
  346. // Execute Command
  347. int ret = callback();
  348. root["result"] = ret;
  349. // Exit early if configure didn't generate a query
  350. if (reloadQueriesAfterCommand) {
  351. this->LoadQueries();
  352. if (!this->hasQuery) {
  353. return ret;
  354. }
  355. if (this->HasQuery(
  356. cmInstrumentationQuery::Query::DynamicSystemInformation)) {
  357. root["dynamicSystemInformation"] = Json::objectValue;
  358. root["dynamicSystemInformation"]["beforeHostMemoryUsed"] =
  359. preConfigureMemory;
  360. root["dynamicSystemInformation"]["beforeCPULoadAverage"] =
  361. preConfigureLoad;
  362. }
  363. }
  364. // Post-Command
  365. this->InsertTimingData(root, steady_start, system_start);
  366. if (this->HasQuery(
  367. cmInstrumentationQuery::Query::DynamicSystemInformation)) {
  368. this->InsertDynamicSystemInformation(root, "after");
  369. }
  370. // Gather additional data
  371. if (options.has_value()) {
  372. for (auto const& item : options.value()) {
  373. if (item.first == "role" && !item.second.empty()) {
  374. command_type = item.second;
  375. } else if (!item.second.empty()) {
  376. root[item.first] = item.second;
  377. }
  378. }
  379. }
  380. if (arrayOptions.has_value()) {
  381. for (auto const& item : arrayOptions.value()) {
  382. if (item.first == "targetLabels" && command_type != "link") {
  383. continue;
  384. }
  385. root[item.first] = Json::arrayValue;
  386. std::stringstream ss(item.second);
  387. std::string element;
  388. while (getline(ss, element, ',')) {
  389. root[item.first].append(element);
  390. }
  391. if (item.first == "outputs") {
  392. root["outputSizes"] = Json::arrayValue;
  393. for (auto const& output : root["outputs"]) {
  394. root["outputSizes"].append(
  395. static_cast<Json::Value::UInt64>(cmSystemTools::FileLength(
  396. cmStrCat(this->binaryDir, "/", output.asCString()))));
  397. }
  398. }
  399. }
  400. }
  401. root["role"] = command_type;
  402. root["binaryDir"] = this->binaryDir;
  403. // Write Json
  404. std::string const& file_name =
  405. cmStrCat(command_type, "-", this->ComputeSuffixHash(command_str),
  406. this->ComputeSuffixTime(), ".json");
  407. this->WriteInstrumentationJson(root, "data", file_name);
  408. return ret;
  409. }
  410. std::string cmInstrumentation::GetCommandStr(
  411. std::vector<std::string> const& args)
  412. {
  413. std::string command_str;
  414. for (size_t i = 0; i < args.size(); ++i) {
  415. command_str = cmStrCat(command_str, args[i]);
  416. if (i < args.size() - 1) {
  417. command_str = cmStrCat(command_str, ' ');
  418. }
  419. }
  420. return command_str;
  421. }
  422. std::string cmInstrumentation::ComputeSuffixHash(
  423. std::string const& command_str)
  424. {
  425. cmCryptoHash hasher(cmCryptoHash::AlgoSHA3_256);
  426. std::string hash = hasher.HashString(command_str);
  427. hash.resize(20, '0');
  428. return hash;
  429. }
  430. std::string cmInstrumentation::ComputeSuffixTime()
  431. {
  432. std::chrono::milliseconds ms =
  433. std::chrono::duration_cast<std::chrono::milliseconds>(
  434. std::chrono::system_clock::now().time_since_epoch());
  435. std::chrono::seconds s =
  436. std::chrono::duration_cast<std::chrono::seconds>(ms);
  437. std::time_t ts = s.count();
  438. std::size_t tms = ms.count() % 1000;
  439. cmTimestamp cmts;
  440. std::ostringstream ss;
  441. ss << cmts.CreateTimestampFromTimeT(ts, "%Y-%m-%dT%H-%M-%S", true) << '-'
  442. << std::setfill('0') << std::setw(4) << tms;
  443. return ss.str();
  444. }
  445. /*
  446. * Called by ctest --start-instrumentation as part of the START_INSTRUMENTATION
  447. * rule when using the Ninja generator.
  448. * This creates a detached process which waits for the Ninja process to die
  449. * before running the postBuild hook. In this way, the postBuild hook triggers
  450. * after every ninja invocation, regardless of whether the build passed or
  451. * failed.
  452. */
  453. int cmInstrumentation::SpawnBuildDaemon()
  454. {
  455. // preBuild Hook
  456. this->CollectTimingData(cmInstrumentationQuery::Hook::PreBuild);
  457. // postBuild Hook
  458. if (this->HasHook(cmInstrumentationQuery::Hook::PostBuild)) {
  459. auto ninja_pid = uv_os_getppid();
  460. if (ninja_pid) {
  461. std::vector<std::string> args;
  462. args.push_back(cmSystemTools::GetCTestCommand());
  463. args.push_back("--wait-and-collect-instrumentation");
  464. args.push_back(this->binaryDir);
  465. args.push_back(std::to_string(ninja_pid));
  466. auto builder = cmUVProcessChainBuilder().SetDetached().AddCommand(args);
  467. auto chain = builder.Start();
  468. uv_run(&chain.GetLoop(), UV_RUN_DEFAULT);
  469. }
  470. }
  471. return 0;
  472. }
  473. /*
  474. * Always called by ctest --wait-and-collect-instrumentation in a detached
  475. * process. Waits for the given PID to end before running the postBuild hook.
  476. *
  477. * See SpawnBuildDaemon()
  478. */
  479. int cmInstrumentation::CollectTimingAfterBuild(int ppid)
  480. {
  481. while (0 == uv_kill(ppid, 0)) {
  482. };
  483. return this->CollectTimingData(cmInstrumentationQuery::Hook::PostBuild);
  484. }