cmInstrumentation.cxx 15 KB

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