cmFileAPI.cxx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #include "cmFileAPI.h"
  4. #include "cmAlgorithms.h"
  5. #include "cmCryptoHash.h"
  6. #include "cmGlobalGenerator.h"
  7. #include "cmSystemTools.h"
  8. #include "cmTimestamp.h"
  9. #include "cmake.h"
  10. #include "cmsys/Directory.hxx"
  11. #include "cmsys/FStream.hxx"
  12. #include <algorithm>
  13. #include <cassert>
  14. #include <chrono>
  15. #include <ctime>
  16. #include <iomanip>
  17. #include <sstream>
  18. #include <utility>
  19. cmFileAPI::cmFileAPI(cmake* cm)
  20. : CMakeInstance(cm)
  21. {
  22. this->APIv1 =
  23. this->CMakeInstance->GetHomeOutputDirectory() + "/.cmake/api/v1";
  24. Json::CharReaderBuilder rbuilder;
  25. rbuilder["collectComments"] = false;
  26. rbuilder["failIfExtra"] = true;
  27. rbuilder["rejectDupKeys"] = false;
  28. rbuilder["strictRoot"] = true;
  29. this->JsonReader =
  30. std::unique_ptr<Json::CharReader>(rbuilder.newCharReader());
  31. Json::StreamWriterBuilder wbuilder;
  32. wbuilder["indentation"] = "\t";
  33. this->JsonWriter =
  34. std::unique_ptr<Json::StreamWriter>(wbuilder.newStreamWriter());
  35. }
  36. void cmFileAPI::ReadQueries()
  37. {
  38. std::string const query_dir = this->APIv1 + "/query";
  39. this->QueryExists = cmSystemTools::FileIsDirectory(query_dir);
  40. if (!this->QueryExists) {
  41. return;
  42. }
  43. // Load queries at the top level.
  44. std::vector<std::string> queries = cmFileAPI::LoadDir(query_dir);
  45. // Read the queries and save for later.
  46. for (std::string& query : queries) {
  47. if (cmHasLiteralPrefix(query, "client-")) {
  48. this->ReadClient(query);
  49. } else if (!cmFileAPI::ReadQuery(query, this->TopQuery.Known)) {
  50. this->TopQuery.Unknown.push_back(std::move(query));
  51. }
  52. }
  53. }
  54. void cmFileAPI::WriteReplies()
  55. {
  56. if (this->QueryExists) {
  57. cmSystemTools::MakeDirectory(this->APIv1 + "/reply");
  58. this->WriteJsonFile(this->BuildReplyIndex(), "index", ComputeSuffixTime);
  59. }
  60. this->RemoveOldReplyFiles();
  61. }
  62. std::vector<std::string> cmFileAPI::LoadDir(std::string const& dir)
  63. {
  64. std::vector<std::string> files;
  65. cmsys::Directory d;
  66. d.Load(dir);
  67. for (unsigned long i = 0; i < d.GetNumberOfFiles(); ++i) {
  68. std::string f = d.GetFile(i);
  69. if (f != "." && f != "..") {
  70. files.push_back(std::move(f));
  71. }
  72. }
  73. std::sort(files.begin(), files.end());
  74. return files;
  75. }
  76. void cmFileAPI::RemoveOldReplyFiles()
  77. {
  78. std::string const reply_dir = this->APIv1 + "/reply";
  79. std::vector<std::string> files = this->LoadDir(reply_dir);
  80. for (std::string const& f : files) {
  81. if (this->ReplyFiles.find(f) == this->ReplyFiles.end()) {
  82. std::string file = reply_dir + "/" + f;
  83. cmSystemTools::RemoveFile(file);
  84. }
  85. }
  86. }
  87. bool cmFileAPI::ReadJsonFile(std::string const& file, Json::Value& value,
  88. std::string& error)
  89. {
  90. std::vector<char> content;
  91. cmsys::ifstream fin;
  92. if (!cmSystemTools::FileIsDirectory(file)) {
  93. fin.open(file.c_str(), std::ios::binary);
  94. }
  95. auto finEnd = fin.rdbuf()->pubseekoff(0, std::ios::end);
  96. if (finEnd > 0) {
  97. size_t finSize = finEnd;
  98. try {
  99. // Allocate a buffer to read the whole file.
  100. content.resize(finSize);
  101. // Now read the file from the beginning.
  102. fin.seekg(0, std::ios::beg);
  103. fin.read(content.data(), finSize);
  104. } catch (...) {
  105. fin.setstate(std::ios::failbit);
  106. }
  107. }
  108. fin.close();
  109. if (!fin) {
  110. value = Json::Value();
  111. error = "failed to read from file";
  112. return false;
  113. }
  114. // Parse our buffer as json.
  115. if (!this->JsonReader->parse(content.data(), content.data() + content.size(),
  116. &value, &error)) {
  117. value = Json::Value();
  118. return false;
  119. }
  120. return true;
  121. }
  122. std::string cmFileAPI::WriteJsonFile(
  123. Json::Value const& value, std::string const& prefix,
  124. std::string (*computeSuffix)(std::string const&))
  125. {
  126. std::string fileName;
  127. // Write the json file with a temporary name.
  128. std::string const& tmpFile = this->APIv1 + "/tmp.json";
  129. cmsys::ofstream ftmp(tmpFile.c_str());
  130. this->JsonWriter->write(value, &ftmp);
  131. ftmp << "\n";
  132. ftmp.close();
  133. if (!ftmp) {
  134. cmSystemTools::RemoveFile(tmpFile);
  135. return fileName;
  136. }
  137. // Compute the final name for the file.
  138. fileName = prefix + "-" + computeSuffix(tmpFile) + ".json";
  139. // Create the destination.
  140. std::string file = this->APIv1 + "/reply";
  141. cmSystemTools::MakeDirectory(file);
  142. file += "/";
  143. file += fileName;
  144. // If the final name already exists then assume it has proper content.
  145. // Otherwise, atomically place the reply file at its final name
  146. if (cmSystemTools::FileExists(file, true) ||
  147. !cmSystemTools::RenameFile(tmpFile.c_str(), file.c_str())) {
  148. cmSystemTools::RemoveFile(tmpFile);
  149. }
  150. // Record this among files we have just written.
  151. this->ReplyFiles.insert(fileName);
  152. return fileName;
  153. }
  154. Json::Value cmFileAPI::MaybeJsonFile(Json::Value in, std::string const& prefix)
  155. {
  156. Json::Value out;
  157. if (in.isObject() || in.isArray()) {
  158. out = Json::objectValue;
  159. out["jsonFile"] = this->WriteJsonFile(in, prefix);
  160. } else {
  161. out = std::move(in);
  162. }
  163. return out;
  164. }
  165. std::string cmFileAPI::ComputeSuffixHash(std::string const& file)
  166. {
  167. cmCryptoHash hasher(cmCryptoHash::AlgoSHA3_256);
  168. std::string hash = hasher.HashFile(file);
  169. hash.resize(20, '0');
  170. return hash;
  171. }
  172. std::string cmFileAPI::ComputeSuffixTime(std::string const&)
  173. {
  174. std::chrono::milliseconds ms =
  175. std::chrono::duration_cast<std::chrono::milliseconds>(
  176. std::chrono::system_clock::now().time_since_epoch());
  177. std::chrono::seconds s =
  178. std::chrono::duration_cast<std::chrono::seconds>(ms);
  179. std::time_t ts = s.count();
  180. std::size_t tms = ms.count() % 1000;
  181. cmTimestamp cmts;
  182. std::ostringstream ss;
  183. ss << cmts.CreateTimestampFromTimeT(ts, "%Y-%m-%dT%H-%M-%S", true) << '-'
  184. << std::setfill('0') << std::setw(4) << tms;
  185. return ss.str();
  186. }
  187. bool cmFileAPI::ReadQuery(std::string const& query,
  188. std::vector<Object>& objects)
  189. {
  190. // Parse the "<kind>-" syntax.
  191. std::string::size_type sep_pos = query.find('-');
  192. if (sep_pos == std::string::npos) {
  193. return false;
  194. }
  195. std::string kindName = query.substr(0, sep_pos);
  196. std::string verStr = query.substr(sep_pos + 1);
  197. if (kindName == ObjectKindName(ObjectKind::InternalTest)) {
  198. Object o;
  199. o.Kind = ObjectKind::InternalTest;
  200. if (verStr == "v1") {
  201. o.Version = 1;
  202. } else if (verStr == "v2") {
  203. o.Version = 2;
  204. } else {
  205. return false;
  206. }
  207. objects.push_back(o);
  208. return true;
  209. }
  210. return false;
  211. }
  212. void cmFileAPI::ReadClient(std::string const& client)
  213. {
  214. // Load queries for the client.
  215. std::string clientDir = this->APIv1 + "/query/" + client;
  216. std::vector<std::string> queries = this->LoadDir(clientDir);
  217. // Read the queries and save for later.
  218. ClientQuery& clientQuery = this->ClientQueries[client];
  219. for (std::string& query : queries) {
  220. if (query == "query.json") {
  221. clientQuery.HaveQueryJson = true;
  222. this->ReadClientQuery(client, clientQuery.QueryJson);
  223. } else if (!this->ReadQuery(query, clientQuery.DirQuery.Known)) {
  224. clientQuery.DirQuery.Unknown.push_back(std::move(query));
  225. }
  226. }
  227. }
  228. void cmFileAPI::ReadClientQuery(std::string const& client, ClientQueryJson& q)
  229. {
  230. // Read the query.json file.
  231. std::string queryFile = this->APIv1 + "/query/" + client + "/query.json";
  232. Json::Value query;
  233. if (!this->ReadJsonFile(queryFile, query, q.Error)) {
  234. return;
  235. }
  236. if (!query.isObject()) {
  237. q.Error = "query root is not an object";
  238. return;
  239. }
  240. Json::Value const& clientValue = query["client"];
  241. if (!clientValue.isNull()) {
  242. q.ClientValue = clientValue;
  243. }
  244. q.RequestsValue = std::move(query["requests"]);
  245. q.Requests = this->BuildClientRequests(q.RequestsValue);
  246. }
  247. Json::Value cmFileAPI::BuildReplyIndex()
  248. {
  249. Json::Value index(Json::objectValue);
  250. // Report information about this version of CMake.
  251. index["cmake"] = this->BuildCMake();
  252. // Reply to all queries that we loaded.
  253. Json::Value& reply = index["reply"] = this->BuildReply(this->TopQuery);
  254. for (auto const& client : this->ClientQueries) {
  255. std::string const& clientName = client.first;
  256. ClientQuery const& clientQuery = client.second;
  257. reply[clientName] = this->BuildClientReply(clientQuery);
  258. }
  259. // Move our index of generated objects into its field.
  260. Json::Value& objects = index["objects"] = Json::arrayValue;
  261. for (auto& entry : this->ReplyIndexObjects) {
  262. objects.append(std::move(entry.second)); // NOLINT(*)
  263. }
  264. return index;
  265. }
  266. Json::Value cmFileAPI::BuildCMake()
  267. {
  268. Json::Value cmake = Json::objectValue;
  269. cmake["version"] = this->CMakeInstance->ReportVersionJson();
  270. Json::Value& cmake_paths = cmake["paths"] = Json::objectValue;
  271. cmake_paths["cmake"] = cmSystemTools::GetCMakeCommand();
  272. cmake_paths["ctest"] = cmSystemTools::GetCTestCommand();
  273. cmake_paths["cpack"] = cmSystemTools::GetCPackCommand();
  274. cmake_paths["root"] = cmSystemTools::GetCMakeRoot();
  275. cmake["generator"] = this->CMakeInstance->GetGlobalGenerator()->GetJson();
  276. return cmake;
  277. }
  278. Json::Value cmFileAPI::BuildReply(Query const& q)
  279. {
  280. Json::Value reply = Json::objectValue;
  281. for (Object const& o : q.Known) {
  282. std::string const& name = ObjectName(o);
  283. reply[name] = this->AddReplyIndexObject(o);
  284. }
  285. for (std::string const& name : q.Unknown) {
  286. reply[name] = cmFileAPI::BuildReplyError("unknown query file");
  287. }
  288. return reply;
  289. }
  290. Json::Value cmFileAPI::BuildReplyError(std::string const& error)
  291. {
  292. Json::Value e = Json::objectValue;
  293. e["error"] = error;
  294. return e;
  295. }
  296. Json::Value const& cmFileAPI::AddReplyIndexObject(Object const& o)
  297. {
  298. Json::Value& indexEntry = this->ReplyIndexObjects[o];
  299. if (!indexEntry.isNull()) {
  300. // The reply object has already been generated.
  301. return indexEntry;
  302. }
  303. // Generate this reply object.
  304. Json::Value const& object = this->BuildObject(o);
  305. assert(object.isObject());
  306. // Populate this index entry.
  307. indexEntry = Json::objectValue;
  308. indexEntry["kind"] = object["kind"];
  309. indexEntry["version"] = object["version"];
  310. indexEntry["jsonFile"] = this->WriteJsonFile(object, ObjectName(o));
  311. return indexEntry;
  312. }
  313. const char* cmFileAPI::ObjectKindName(ObjectKind kind)
  314. {
  315. // Keep in sync with ObjectKind enum.
  316. static const char* objectKindNames[] = {
  317. "__test" //
  318. };
  319. return objectKindNames[size_t(kind)];
  320. }
  321. std::string cmFileAPI::ObjectName(Object const& o)
  322. {
  323. std::string name = ObjectKindName(o.Kind);
  324. name += "-v";
  325. name += std::to_string(o.Version);
  326. return name;
  327. }
  328. Json::Value cmFileAPI::BuildObject(Object const& object)
  329. {
  330. Json::Value value;
  331. switch (object.Kind) {
  332. case ObjectKind::InternalTest:
  333. value = this->BuildInternalTest(object);
  334. break;
  335. }
  336. return value;
  337. }
  338. cmFileAPI::ClientRequests cmFileAPI::BuildClientRequests(
  339. Json::Value const& requests)
  340. {
  341. ClientRequests result;
  342. if (requests.isNull()) {
  343. result.Error = "'requests' member missing";
  344. return result;
  345. }
  346. if (!requests.isArray()) {
  347. result.Error = "'requests' member is not an array";
  348. return result;
  349. }
  350. result.reserve(requests.size());
  351. for (Json::Value const& request : requests) {
  352. result.emplace_back(this->BuildClientRequest(request));
  353. }
  354. return result;
  355. }
  356. cmFileAPI::ClientRequest cmFileAPI::BuildClientRequest(
  357. Json::Value const& request)
  358. {
  359. ClientRequest r;
  360. if (!request.isObject()) {
  361. r.Error = "request is not an object";
  362. return r;
  363. }
  364. Json::Value const& kind = request["kind"];
  365. if (kind.isNull()) {
  366. r.Error = "'kind' member missing";
  367. return r;
  368. }
  369. if (!kind.isString()) {
  370. r.Error = "'kind' member is not a string";
  371. return r;
  372. }
  373. std::string const& kindName = kind.asString();
  374. if (kindName == this->ObjectKindName(ObjectKind::InternalTest)) {
  375. r.Kind = ObjectKind::InternalTest;
  376. } else {
  377. r.Error = "unknown request kind '" + kindName + "'";
  378. return r;
  379. }
  380. Json::Value const& version = request["version"];
  381. if (version.isNull()) {
  382. r.Error = "'version' member missing";
  383. return r;
  384. }
  385. std::vector<RequestVersion> versions;
  386. if (!cmFileAPI::ReadRequestVersions(version, versions, r.Error)) {
  387. return r;
  388. }
  389. switch (r.Kind) {
  390. case ObjectKind::InternalTest:
  391. this->BuildClientRequestInternalTest(r, versions);
  392. break;
  393. }
  394. return r;
  395. }
  396. Json::Value cmFileAPI::BuildClientReply(ClientQuery const& q)
  397. {
  398. Json::Value reply = this->BuildReply(q.DirQuery);
  399. if (!q.HaveQueryJson) {
  400. return reply;
  401. }
  402. Json::Value& reply_query_json = reply["query.json"];
  403. ClientQueryJson const& qj = q.QueryJson;
  404. if (!qj.Error.empty()) {
  405. reply_query_json = this->BuildReplyError(qj.Error);
  406. return reply;
  407. }
  408. if (!qj.ClientValue.isNull()) {
  409. reply_query_json["client"] = qj.ClientValue;
  410. }
  411. if (!qj.RequestsValue.isNull()) {
  412. reply_query_json["requests"] = qj.RequestsValue;
  413. }
  414. reply_query_json["responses"] = this->BuildClientReplyResponses(qj.Requests);
  415. return reply;
  416. }
  417. Json::Value cmFileAPI::BuildClientReplyResponses(
  418. ClientRequests const& requests)
  419. {
  420. Json::Value responses;
  421. if (!requests.Error.empty()) {
  422. responses = this->BuildReplyError(requests.Error);
  423. return responses;
  424. }
  425. responses = Json::arrayValue;
  426. for (ClientRequest const& request : requests) {
  427. responses.append(this->BuildClientReplyResponse(request));
  428. }
  429. return responses;
  430. }
  431. Json::Value cmFileAPI::BuildClientReplyResponse(ClientRequest const& request)
  432. {
  433. Json::Value response;
  434. if (!request.Error.empty()) {
  435. response = this->BuildReplyError(request.Error);
  436. return response;
  437. }
  438. response = this->AddReplyIndexObject(request);
  439. return response;
  440. }
  441. bool cmFileAPI::ReadRequestVersions(Json::Value const& version,
  442. std::vector<RequestVersion>& versions,
  443. std::string& error)
  444. {
  445. if (version.isArray()) {
  446. for (Json::Value const& v : version) {
  447. if (!ReadRequestVersion(v, /*inArray=*/true, versions, error)) {
  448. return false;
  449. }
  450. }
  451. } else {
  452. if (!ReadRequestVersion(version, /*inArray=*/false, versions, error)) {
  453. return false;
  454. }
  455. }
  456. return true;
  457. }
  458. bool cmFileAPI::ReadRequestVersion(Json::Value const& version, bool inArray,
  459. std::vector<RequestVersion>& result,
  460. std::string& error)
  461. {
  462. if (version.isUInt()) {
  463. RequestVersion v;
  464. v.Major = version.asUInt();
  465. result.push_back(v);
  466. return true;
  467. }
  468. if (!version.isObject()) {
  469. if (inArray) {
  470. error = "'version' array entry is not a non-negative integer or object";
  471. } else {
  472. error =
  473. "'version' member is not a non-negative integer, object, or array";
  474. }
  475. return false;
  476. }
  477. Json::Value const& major = version["major"];
  478. if (major.isNull()) {
  479. error = "'version' object 'major' member missing";
  480. return false;
  481. }
  482. if (!major.isUInt()) {
  483. error = "'version' object 'major' member is not a non-negative integer";
  484. return false;
  485. }
  486. RequestVersion v;
  487. v.Major = major.asUInt();
  488. Json::Value const& minor = version["minor"];
  489. if (minor.isUInt()) {
  490. v.Minor = minor.asUInt();
  491. } else if (!minor.isNull()) {
  492. error = "'version' object 'minor' member is not a non-negative integer";
  493. return false;
  494. }
  495. result.push_back(v);
  496. return true;
  497. }
  498. std::string cmFileAPI::NoSupportedVersion(
  499. std::vector<RequestVersion> const& versions)
  500. {
  501. std::ostringstream msg;
  502. msg << "no supported version specified";
  503. if (!versions.empty()) {
  504. msg << " among:";
  505. for (RequestVersion const& v : versions) {
  506. msg << " " << v.Major << "." << v.Minor;
  507. }
  508. }
  509. return msg.str();
  510. }
  511. // The "__test" object kind is for internal testing of CMake.
  512. static unsigned int const InternalTestV1Minor = 3;
  513. static unsigned int const InternalTestV2Minor = 0;
  514. void cmFileAPI::BuildClientRequestInternalTest(
  515. ClientRequest& r, std::vector<RequestVersion> const& versions)
  516. {
  517. // Select a known version from those requested.
  518. for (RequestVersion const& v : versions) {
  519. if ((v.Major == 1 && v.Minor <= InternalTestV1Minor) || //
  520. (v.Major == 2 && v.Minor <= InternalTestV2Minor)) {
  521. r.Version = v.Major;
  522. break;
  523. }
  524. }
  525. if (!r.Version) {
  526. r.Error = NoSupportedVersion(versions);
  527. }
  528. }
  529. Json::Value cmFileAPI::BuildInternalTest(Object const& object)
  530. {
  531. Json::Value test = Json::objectValue;
  532. test["kind"] = this->ObjectKindName(object.Kind);
  533. Json::Value& version = test["version"] = Json::objectValue;
  534. if (object.Version == 2) {
  535. version["major"] = 2;
  536. version["minor"] = InternalTestV2Minor;
  537. } else {
  538. version["major"] = 1;
  539. version["minor"] = InternalTestV1Minor;
  540. }
  541. return test;
  542. }