cmInstrumentation.cxx 15 KB

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