cmFileAPI.cxx 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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 "cmSystemTools.h"
  7. #include "cmTimestamp.h"
  8. #include "cmake.h"
  9. #include "cmsys/Directory.hxx"
  10. #include "cmsys/FStream.hxx"
  11. #include <algorithm>
  12. #include <cassert>
  13. #include <chrono>
  14. #include <ctime>
  15. #include <iomanip>
  16. #include <sstream>
  17. #include <utility>
  18. cmFileAPI::cmFileAPI(cmake* cm)
  19. : CMakeInstance(cm)
  20. {
  21. this->APIv1 =
  22. this->CMakeInstance->GetHomeOutputDirectory() + "/.cmake/api/v1";
  23. Json::StreamWriterBuilder wbuilder;
  24. wbuilder["indentation"] = "\t";
  25. this->JsonWriter =
  26. std::unique_ptr<Json::StreamWriter>(wbuilder.newStreamWriter());
  27. }
  28. void cmFileAPI::ReadQueries()
  29. {
  30. std::string const query_dir = this->APIv1 + "/query";
  31. this->QueryExists = cmSystemTools::FileIsDirectory(query_dir);
  32. if (!this->QueryExists) {
  33. return;
  34. }
  35. // Load queries at the top level.
  36. std::vector<std::string> queries = cmFileAPI::LoadDir(query_dir);
  37. // Read the queries and save for later.
  38. for (std::string& query : queries) {
  39. if (cmHasLiteralPrefix(query, "client-")) {
  40. this->ReadClient(query);
  41. } else if (!cmFileAPI::ReadQuery(query, this->TopQuery.Known)) {
  42. this->TopQuery.Unknown.push_back(std::move(query));
  43. }
  44. }
  45. }
  46. void cmFileAPI::WriteReplies()
  47. {
  48. if (this->QueryExists) {
  49. cmSystemTools::MakeDirectory(this->APIv1 + "/reply");
  50. this->WriteJsonFile(this->BuildReplyIndex(), "index", ComputeSuffixTime);
  51. }
  52. this->RemoveOldReplyFiles();
  53. }
  54. std::vector<std::string> cmFileAPI::LoadDir(std::string const& dir)
  55. {
  56. std::vector<std::string> files;
  57. cmsys::Directory d;
  58. d.Load(dir);
  59. for (unsigned long i = 0; i < d.GetNumberOfFiles(); ++i) {
  60. std::string f = d.GetFile(i);
  61. if (f != "." && f != "..") {
  62. files.push_back(std::move(f));
  63. }
  64. }
  65. std::sort(files.begin(), files.end());
  66. return files;
  67. }
  68. void cmFileAPI::RemoveOldReplyFiles()
  69. {
  70. std::string const reply_dir = this->APIv1 + "/reply";
  71. std::vector<std::string> files = this->LoadDir(reply_dir);
  72. for (std::string const& f : files) {
  73. if (this->ReplyFiles.find(f) == this->ReplyFiles.end()) {
  74. std::string file = reply_dir + "/" + f;
  75. cmSystemTools::RemoveFile(file);
  76. }
  77. }
  78. }
  79. std::string cmFileAPI::WriteJsonFile(
  80. Json::Value const& value, std::string const& prefix,
  81. std::string (*computeSuffix)(std::string const&))
  82. {
  83. std::string fileName;
  84. // Write the json file with a temporary name.
  85. std::string const& tmpFile = this->APIv1 + "/tmp.json";
  86. cmsys::ofstream ftmp(tmpFile.c_str());
  87. this->JsonWriter->write(value, &ftmp);
  88. ftmp << "\n";
  89. ftmp.close();
  90. if (!ftmp) {
  91. cmSystemTools::RemoveFile(tmpFile);
  92. return fileName;
  93. }
  94. // Compute the final name for the file.
  95. fileName = prefix + "-" + computeSuffix(tmpFile) + ".json";
  96. // Create the destination.
  97. std::string file = this->APIv1 + "/reply";
  98. cmSystemTools::MakeDirectory(file);
  99. file += "/";
  100. file += fileName;
  101. // If the final name already exists then assume it has proper content.
  102. // Otherwise, atomically place the reply file at its final name
  103. if (cmSystemTools::FileExists(file, true) ||
  104. !cmSystemTools::RenameFile(tmpFile.c_str(), file.c_str())) {
  105. cmSystemTools::RemoveFile(tmpFile);
  106. }
  107. // Record this among files we have just written.
  108. this->ReplyFiles.insert(fileName);
  109. return fileName;
  110. }
  111. std::string cmFileAPI::ComputeSuffixHash(std::string const& file)
  112. {
  113. cmCryptoHash hasher(cmCryptoHash::AlgoSHA3_256);
  114. std::string hash = hasher.HashFile(file);
  115. hash.resize(20, '0');
  116. return hash;
  117. }
  118. std::string cmFileAPI::ComputeSuffixTime(std::string const&)
  119. {
  120. std::chrono::milliseconds ms =
  121. std::chrono::duration_cast<std::chrono::milliseconds>(
  122. std::chrono::system_clock::now().time_since_epoch());
  123. std::chrono::seconds s =
  124. std::chrono::duration_cast<std::chrono::seconds>(ms);
  125. std::time_t ts = s.count();
  126. std::size_t tms = ms.count() % 1000;
  127. cmTimestamp cmts;
  128. std::ostringstream ss;
  129. ss << cmts.CreateTimestampFromTimeT(ts, "%Y-%m-%dT%H-%M-%S", true) << '-'
  130. << std::setfill('0') << std::setw(4) << tms;
  131. return ss.str();
  132. }
  133. bool cmFileAPI::ReadQuery(std::string const& query,
  134. std::vector<Object>& objects)
  135. {
  136. // Parse the "<kind>-" syntax.
  137. std::string::size_type sep_pos = query.find('-');
  138. if (sep_pos == std::string::npos) {
  139. return false;
  140. }
  141. std::string kindName = query.substr(0, sep_pos);
  142. std::string verStr = query.substr(sep_pos + 1);
  143. if (kindName == ObjectKindName(ObjectKind::InternalTest)) {
  144. Object o;
  145. o.Kind = ObjectKind::InternalTest;
  146. if (verStr == "v1") {
  147. o.Version = 1;
  148. } else if (verStr == "v2") {
  149. o.Version = 2;
  150. } else {
  151. return false;
  152. }
  153. objects.push_back(o);
  154. return true;
  155. }
  156. return false;
  157. }
  158. void cmFileAPI::ReadClient(std::string const& client)
  159. {
  160. // Load queries for the client.
  161. std::string clientDir = this->APIv1 + "/query/" + client;
  162. std::vector<std::string> queries = this->LoadDir(clientDir);
  163. // Read the queries and save for later.
  164. Query& clientQuery = this->ClientQueries[client];
  165. for (std::string& query : queries) {
  166. if (!this->ReadQuery(query, clientQuery.Known)) {
  167. clientQuery.Unknown.push_back(std::move(query));
  168. }
  169. }
  170. }
  171. Json::Value cmFileAPI::BuildReplyIndex()
  172. {
  173. Json::Value index(Json::objectValue);
  174. // Report information about this version of CMake.
  175. index["cmake"] = this->BuildCMake();
  176. // Reply to all queries that we loaded.
  177. Json::Value& reply = index["reply"] = this->BuildReply(this->TopQuery);
  178. for (auto const& client : this->ClientQueries) {
  179. std::string const& clientName = client.first;
  180. Query const& clientQuery = client.second;
  181. reply[clientName] = this->BuildReply(clientQuery);
  182. }
  183. // Move our index of generated objects into its field.
  184. Json::Value& objects = index["objects"] = Json::arrayValue;
  185. for (auto& entry : this->ReplyIndexObjects) {
  186. objects.append(std::move(entry.second)); // NOLINT(*)
  187. }
  188. return index;
  189. }
  190. Json::Value cmFileAPI::BuildCMake()
  191. {
  192. Json::Value cmake = Json::objectValue;
  193. cmake["version"] = this->CMakeInstance->ReportVersionJson();
  194. Json::Value& cmake_paths = cmake["paths"] = Json::objectValue;
  195. cmake_paths["cmake"] = cmSystemTools::GetCMakeCommand();
  196. cmake_paths["ctest"] = cmSystemTools::GetCTestCommand();
  197. cmake_paths["cpack"] = cmSystemTools::GetCPackCommand();
  198. cmake_paths["root"] = cmSystemTools::GetCMakeRoot();
  199. return cmake;
  200. }
  201. Json::Value cmFileAPI::BuildReply(Query const& q)
  202. {
  203. Json::Value reply = Json::objectValue;
  204. for (Object const& o : q.Known) {
  205. std::string const& name = ObjectName(o);
  206. reply[name] = this->AddReplyIndexObject(o);
  207. }
  208. for (std::string const& name : q.Unknown) {
  209. reply[name] = cmFileAPI::BuildReplyError("unknown query file");
  210. }
  211. return reply;
  212. }
  213. Json::Value cmFileAPI::BuildReplyError(std::string const& error)
  214. {
  215. Json::Value e = Json::objectValue;
  216. e["error"] = error;
  217. return e;
  218. }
  219. Json::Value const& cmFileAPI::AddReplyIndexObject(Object const& o)
  220. {
  221. Json::Value& indexEntry = this->ReplyIndexObjects[o];
  222. if (!indexEntry.isNull()) {
  223. // The reply object has already been generated.
  224. return indexEntry;
  225. }
  226. // Generate this reply object.
  227. Json::Value const& object = this->BuildObject(o);
  228. assert(object.isObject());
  229. // Populate this index entry.
  230. indexEntry = Json::objectValue;
  231. indexEntry["kind"] = object["kind"];
  232. indexEntry["version"] = object["version"];
  233. indexEntry["jsonFile"] = this->WriteJsonFile(object, ObjectName(o));
  234. return indexEntry;
  235. }
  236. const char* cmFileAPI::ObjectKindName(ObjectKind kind)
  237. {
  238. // Keep in sync with ObjectKind enum.
  239. static const char* objectKindNames[] = {
  240. "__test" //
  241. };
  242. return objectKindNames[size_t(kind)];
  243. }
  244. std::string cmFileAPI::ObjectName(Object const& o)
  245. {
  246. std::string name = ObjectKindName(o.Kind);
  247. name += "-v";
  248. name += std::to_string(o.Version);
  249. return name;
  250. }
  251. Json::Value cmFileAPI::BuildObject(Object const& object)
  252. {
  253. Json::Value value;
  254. switch (object.Kind) {
  255. case ObjectKind::InternalTest:
  256. value = this->BuildInternalTest(object);
  257. break;
  258. }
  259. return value;
  260. }
  261. // The "__test" object kind is for internal testing of CMake.
  262. static unsigned int const InternalTestV1Minor = 3;
  263. static unsigned int const InternalTestV2Minor = 0;
  264. Json::Value cmFileAPI::BuildInternalTest(Object const& object)
  265. {
  266. Json::Value test = Json::objectValue;
  267. test["kind"] = this->ObjectKindName(object.Kind);
  268. Json::Value& version = test["version"] = Json::objectValue;
  269. if (object.Version == 2) {
  270. version["major"] = 2;
  271. version["minor"] = InternalTestV2Minor;
  272. } else {
  273. version["major"] = 1;
  274. version["minor"] = InternalTestV1Minor;
  275. }
  276. return test;
  277. }