cmServer.cxx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  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 "cmServer.h"
  4. #include "cmAlgorithms.h"
  5. #include "cmConnection.h"
  6. #include "cmFileMonitor.h"
  7. #include "cmJsonObjectDictionary.h"
  8. #include "cmServerDictionary.h"
  9. #include "cmServerProtocol.h"
  10. #include "cmSystemTools.h"
  11. #include "cm_jsoncpp_reader.h"
  12. #include "cm_jsoncpp_writer.h"
  13. #include "cmake.h"
  14. #include "cmsys/FStream.hxx"
  15. #include <algorithm>
  16. #include <cassert>
  17. #include <cstdint>
  18. #include <iostream>
  19. #include <memory>
  20. #include <mutex>
  21. #include <utility>
  22. void on_signal(uv_signal_t* signal, int signum)
  23. {
  24. auto conn = static_cast<cmServerBase*>(signal->data);
  25. conn->OnSignal(signum);
  26. }
  27. static void on_walk_to_shutdown(uv_handle_t* handle, void* arg)
  28. {
  29. (void)arg;
  30. assert(uv_is_closing(handle));
  31. if (!uv_is_closing(handle)) {
  32. uv_close(handle, &cmEventBasedConnection::on_close);
  33. }
  34. }
  35. class cmServer::DebugInfo
  36. {
  37. public:
  38. DebugInfo()
  39. : StartTime(uv_hrtime())
  40. {
  41. }
  42. bool PrintStatistics = false;
  43. std::string OutputFile;
  44. uint64_t StartTime;
  45. };
  46. cmServer::cmServer(cmConnection* conn, bool supportExperimental)
  47. : cmServerBase(conn)
  48. , SupportExperimental(supportExperimental)
  49. {
  50. // Register supported protocols:
  51. this->RegisterProtocol(new cmServerProtocol1);
  52. }
  53. cmServer::~cmServer()
  54. {
  55. Close();
  56. for (cmServerProtocol* p : this->SupportedProtocols) {
  57. delete p;
  58. }
  59. }
  60. void cmServer::ProcessRequest(cmConnection* connection,
  61. const std::string& input)
  62. {
  63. Json::Reader reader;
  64. Json::Value value;
  65. if (!reader.parse(input, value)) {
  66. this->WriteParseError(connection, "Failed to parse JSON input.");
  67. return;
  68. }
  69. std::unique_ptr<DebugInfo> debug;
  70. Json::Value debugValue = value["debug"];
  71. if (!debugValue.isNull()) {
  72. debug = cm::make_unique<DebugInfo>();
  73. debug->OutputFile = debugValue["dumpToFile"].asString();
  74. debug->PrintStatistics = debugValue["showStats"].asBool();
  75. }
  76. const cmServerRequest request(this, connection, value[kTYPE_KEY].asString(),
  77. value[kCOOKIE_KEY].asString(), value);
  78. if (request.Type.empty()) {
  79. cmServerResponse response(request);
  80. response.SetError("No type given in request.");
  81. this->WriteResponse(connection, response, nullptr);
  82. return;
  83. }
  84. cmSystemTools::SetMessageCallback(
  85. [&request](const std::string& msg, const char* title) {
  86. reportMessage(msg, title, request);
  87. });
  88. if (this->Protocol) {
  89. this->Protocol->CMakeInstance()->SetProgressCallback(
  90. [&request](const char* msg, float prog) {
  91. reportProgress(msg, prog, request);
  92. });
  93. this->WriteResponse(connection, this->Protocol->Process(request),
  94. debug.get());
  95. } else {
  96. this->WriteResponse(connection, this->SetProtocolVersion(request),
  97. debug.get());
  98. }
  99. }
  100. void cmServer::RegisterProtocol(cmServerProtocol* protocol)
  101. {
  102. if (protocol->IsExperimental() && !this->SupportExperimental) {
  103. delete protocol;
  104. return;
  105. }
  106. auto version = protocol->ProtocolVersion();
  107. assert(version.first >= 0);
  108. assert(version.second >= 0);
  109. auto it = std::find_if(this->SupportedProtocols.begin(),
  110. this->SupportedProtocols.end(),
  111. [version](cmServerProtocol* p) {
  112. return p->ProtocolVersion() == version;
  113. });
  114. if (it == this->SupportedProtocols.end()) {
  115. this->SupportedProtocols.push_back(protocol);
  116. }
  117. }
  118. void cmServer::PrintHello(cmConnection* connection) const
  119. {
  120. Json::Value hello = Json::objectValue;
  121. hello[kTYPE_KEY] = "hello";
  122. Json::Value& protocolVersions = hello[kSUPPORTED_PROTOCOL_VERSIONS] =
  123. Json::arrayValue;
  124. for (auto const& proto : this->SupportedProtocols) {
  125. auto version = proto->ProtocolVersion();
  126. Json::Value tmp = Json::objectValue;
  127. tmp[kMAJOR_KEY] = version.first;
  128. tmp[kMINOR_KEY] = version.second;
  129. if (proto->IsExperimental()) {
  130. tmp[kIS_EXPERIMENTAL_KEY] = true;
  131. }
  132. protocolVersions.append(tmp);
  133. }
  134. this->WriteJsonObject(connection, hello, nullptr);
  135. }
  136. void cmServer::reportProgress(const char* msg, float progress,
  137. const cmServerRequest& request)
  138. {
  139. if (progress < 0.0f || progress > 1.0f) {
  140. request.ReportMessage(msg, "");
  141. } else {
  142. request.ReportProgress(0, static_cast<int>(progress * 1000), 1000, msg);
  143. }
  144. }
  145. void cmServer::reportMessage(const std::string& msg, const char* title,
  146. const cmServerRequest& request)
  147. {
  148. std::string titleString;
  149. if (title) {
  150. titleString = title;
  151. }
  152. request.ReportMessage(msg, titleString);
  153. }
  154. cmServerResponse cmServer::SetProtocolVersion(const cmServerRequest& request)
  155. {
  156. if (request.Type != kHANDSHAKE_TYPE) {
  157. return request.ReportError("Waiting for type \"" + kHANDSHAKE_TYPE +
  158. "\".");
  159. }
  160. Json::Value requestedProtocolVersion = request.Data[kPROTOCOL_VERSION_KEY];
  161. if (requestedProtocolVersion.isNull()) {
  162. return request.ReportError("\"" + kPROTOCOL_VERSION_KEY +
  163. "\" is required for \"" + kHANDSHAKE_TYPE +
  164. "\".");
  165. }
  166. if (!requestedProtocolVersion.isObject()) {
  167. return request.ReportError("\"" + kPROTOCOL_VERSION_KEY +
  168. "\" must be a JSON object.");
  169. }
  170. Json::Value majorValue = requestedProtocolVersion[kMAJOR_KEY];
  171. if (!majorValue.isInt()) {
  172. return request.ReportError("\"" + kMAJOR_KEY +
  173. "\" must be set and an integer.");
  174. }
  175. Json::Value minorValue = requestedProtocolVersion[kMINOR_KEY];
  176. if (!minorValue.isNull() && !minorValue.isInt()) {
  177. return request.ReportError("\"" + kMINOR_KEY +
  178. "\" must be unset or an integer.");
  179. }
  180. const int major = majorValue.asInt();
  181. const int minor = minorValue.isNull() ? -1 : minorValue.asInt();
  182. if (major < 0) {
  183. return request.ReportError("\"" + kMAJOR_KEY + "\" must be >= 0.");
  184. }
  185. if (!minorValue.isNull() && minor < 0) {
  186. return request.ReportError("\"" + kMINOR_KEY +
  187. "\" must be >= 0 when set.");
  188. }
  189. this->Protocol =
  190. cmServer::FindMatchingProtocol(this->SupportedProtocols, major, minor);
  191. if (!this->Protocol) {
  192. return request.ReportError("Protocol version not supported.");
  193. }
  194. std::string errorMessage;
  195. if (!this->Protocol->Activate(this, request, &errorMessage)) {
  196. this->Protocol = nullptr;
  197. return request.ReportError("Failed to activate protocol version: " +
  198. errorMessage);
  199. }
  200. return request.Reply(Json::objectValue);
  201. }
  202. bool cmServer::Serve(std::string* errorMessage)
  203. {
  204. if (this->SupportedProtocols.empty()) {
  205. *errorMessage =
  206. "No protocol versions defined. Maybe you need --experimental?";
  207. return false;
  208. }
  209. assert(!this->Protocol);
  210. return cmServerBase::Serve(errorMessage);
  211. }
  212. cmFileMonitor* cmServer::FileMonitor() const
  213. {
  214. return fileMonitor.get();
  215. }
  216. void cmServer::WriteJsonObject(const Json::Value& jsonValue,
  217. const DebugInfo* debug) const
  218. {
  219. cm::shared_lock<cm::shared_mutex> lock(ConnectionsMutex);
  220. for (auto& connection : this->Connections) {
  221. WriteJsonObject(connection.get(), jsonValue, debug);
  222. }
  223. }
  224. void cmServer::WriteJsonObject(cmConnection* connection,
  225. const Json::Value& jsonValue,
  226. const DebugInfo* debug) const
  227. {
  228. Json::FastWriter writer;
  229. auto beforeJson = uv_hrtime();
  230. std::string result = writer.write(jsonValue);
  231. if (debug) {
  232. Json::Value copy = jsonValue;
  233. if (debug->PrintStatistics) {
  234. Json::Value stats = Json::objectValue;
  235. auto endTime = uv_hrtime();
  236. stats["jsonSerialization"] = double(endTime - beforeJson) / 1000000.0;
  237. stats["totalTime"] = double(endTime - debug->StartTime) / 1000000.0;
  238. stats["size"] = static_cast<int>(result.size());
  239. if (!debug->OutputFile.empty()) {
  240. stats["dumpFile"] = debug->OutputFile;
  241. }
  242. copy["zzzDebug"] = stats;
  243. result = writer.write(copy); // Update result to include debug info
  244. }
  245. if (!debug->OutputFile.empty()) {
  246. cmsys::ofstream myfile(debug->OutputFile.c_str());
  247. myfile << result;
  248. }
  249. }
  250. connection->WriteData(result);
  251. }
  252. cmServerProtocol* cmServer::FindMatchingProtocol(
  253. const std::vector<cmServerProtocol*>& protocols, int major, int minor)
  254. {
  255. cmServerProtocol* bestMatch = nullptr;
  256. for (auto protocol : protocols) {
  257. auto version = protocol->ProtocolVersion();
  258. if (major != version.first) {
  259. continue;
  260. }
  261. if (minor == version.second) {
  262. return protocol;
  263. }
  264. if (!bestMatch || bestMatch->ProtocolVersion().second < version.second) {
  265. bestMatch = protocol;
  266. }
  267. }
  268. return minor < 0 ? bestMatch : nullptr;
  269. }
  270. void cmServer::WriteProgress(const cmServerRequest& request, int min,
  271. int current, int max,
  272. const std::string& message) const
  273. {
  274. assert(min <= current && current <= max);
  275. assert(message.length() != 0);
  276. Json::Value obj = Json::objectValue;
  277. obj[kTYPE_KEY] = kPROGRESS_TYPE;
  278. obj[kREPLY_TO_KEY] = request.Type;
  279. obj[kCOOKIE_KEY] = request.Cookie;
  280. obj[kPROGRESS_MESSAGE_KEY] = message;
  281. obj[kPROGRESS_MINIMUM_KEY] = min;
  282. obj[kPROGRESS_MAXIMUM_KEY] = max;
  283. obj[kPROGRESS_CURRENT_KEY] = current;
  284. this->WriteJsonObject(request.Connection, obj, nullptr);
  285. }
  286. void cmServer::WriteMessage(const cmServerRequest& request,
  287. const std::string& message,
  288. const std::string& title) const
  289. {
  290. if (message.empty()) {
  291. return;
  292. }
  293. Json::Value obj = Json::objectValue;
  294. obj[kTYPE_KEY] = kMESSAGE_TYPE;
  295. obj[kREPLY_TO_KEY] = request.Type;
  296. obj[kCOOKIE_KEY] = request.Cookie;
  297. obj[kMESSAGE_KEY] = message;
  298. if (!title.empty()) {
  299. obj[kTITLE_KEY] = title;
  300. }
  301. WriteJsonObject(request.Connection, obj, nullptr);
  302. }
  303. void cmServer::WriteParseError(cmConnection* connection,
  304. const std::string& message) const
  305. {
  306. Json::Value obj = Json::objectValue;
  307. obj[kTYPE_KEY] = kERROR_TYPE;
  308. obj[kERROR_MESSAGE_KEY] = message;
  309. obj[kREPLY_TO_KEY] = "";
  310. obj[kCOOKIE_KEY] = "";
  311. this->WriteJsonObject(connection, obj, nullptr);
  312. }
  313. void cmServer::WriteSignal(const std::string& name,
  314. const Json::Value& data) const
  315. {
  316. assert(data.isObject());
  317. Json::Value obj = data;
  318. obj[kTYPE_KEY] = kSIGNAL_TYPE;
  319. obj[kREPLY_TO_KEY] = "";
  320. obj[kCOOKIE_KEY] = "";
  321. obj[kNAME_KEY] = name;
  322. WriteJsonObject(obj, nullptr);
  323. }
  324. void cmServer::WriteResponse(cmConnection* connection,
  325. const cmServerResponse& response,
  326. const DebugInfo* debug) const
  327. {
  328. assert(response.IsComplete());
  329. Json::Value obj = response.Data();
  330. obj[kCOOKIE_KEY] = response.Cookie;
  331. obj[kTYPE_KEY] = response.IsError() ? kERROR_TYPE : kREPLY_TYPE;
  332. obj[kREPLY_TO_KEY] = response.Type;
  333. if (response.IsError()) {
  334. obj[kERROR_MESSAGE_KEY] = response.ErrorMessage();
  335. }
  336. this->WriteJsonObject(connection, obj, debug);
  337. }
  338. void cmServer::OnConnected(cmConnection* connection)
  339. {
  340. PrintHello(connection);
  341. }
  342. void cmServer::OnServeStart()
  343. {
  344. cmServerBase::OnServeStart();
  345. fileMonitor = std::make_shared<cmFileMonitor>(GetLoop());
  346. }
  347. void cmServer::StartShutDown()
  348. {
  349. if (fileMonitor) {
  350. fileMonitor->StopMonitoring();
  351. fileMonitor.reset();
  352. }
  353. cmServerBase::StartShutDown();
  354. }
  355. static void __start_thread(void* arg)
  356. {
  357. auto server = static_cast<cmServerBase*>(arg);
  358. std::string error;
  359. bool success = server->Serve(&error);
  360. if (!success || !error.empty()) {
  361. std::cerr << "Error during serve: " << error << std::endl;
  362. }
  363. }
  364. bool cmServerBase::StartServeThread()
  365. {
  366. ServeThreadRunning = true;
  367. uv_thread_create(&ServeThread, __start_thread, this);
  368. return true;
  369. }
  370. static void __shutdownThread(uv_async_t* arg)
  371. {
  372. auto server = static_cast<cmServerBase*>(arg->data);
  373. server->StartShutDown();
  374. }
  375. bool cmServerBase::Serve(std::string* errorMessage)
  376. {
  377. #ifndef NDEBUG
  378. uv_thread_t blank_thread_t = {};
  379. assert(uv_thread_equal(&blank_thread_t, &ServeThreadId));
  380. ServeThreadId = uv_thread_self();
  381. #endif
  382. errorMessage->clear();
  383. ShutdownSignal.init(Loop, __shutdownThread, this);
  384. SIGINTHandler.init(Loop, this);
  385. SIGHUPHandler.init(Loop, this);
  386. SIGINTHandler.start(&on_signal, SIGINT);
  387. SIGHUPHandler.start(&on_signal, SIGHUP);
  388. OnServeStart();
  389. {
  390. cm::shared_lock<cm::shared_mutex> lock(ConnectionsMutex);
  391. for (auto& connection : Connections) {
  392. if (!connection->OnServeStart(errorMessage)) {
  393. return false;
  394. }
  395. }
  396. }
  397. if (uv_run(&Loop, UV_RUN_DEFAULT) != 0) {
  398. // It is important we don't ever let the event loop exit with open handles
  399. // at best this is a memory leak, but it can also introduce race conditions
  400. // which can hang the program.
  401. assert(false && "Event loop stopped in unclean state.");
  402. *errorMessage = "Internal Error: Event loop stopped in unclean state.";
  403. return false;
  404. }
  405. return true;
  406. }
  407. void cmServerBase::OnConnected(cmConnection*)
  408. {
  409. }
  410. void cmServerBase::OnServeStart()
  411. {
  412. }
  413. void cmServerBase::StartShutDown()
  414. {
  415. ShutdownSignal.reset();
  416. SIGINTHandler.reset();
  417. SIGHUPHandler.reset();
  418. {
  419. std::unique_lock<cm::shared_mutex> lock(ConnectionsMutex);
  420. for (auto& connection : Connections) {
  421. connection->OnConnectionShuttingDown();
  422. }
  423. Connections.clear();
  424. }
  425. uv_walk(&Loop, on_walk_to_shutdown, nullptr);
  426. }
  427. bool cmServerBase::OnSignal(int signum)
  428. {
  429. (void)signum;
  430. StartShutDown();
  431. return true;
  432. }
  433. cmServerBase::cmServerBase(cmConnection* connection)
  434. {
  435. auto err = uv_loop_init(&Loop);
  436. (void)err;
  437. Loop.data = this;
  438. assert(err == 0);
  439. AddNewConnection(connection);
  440. }
  441. void cmServerBase::Close()
  442. {
  443. if (Loop.data) {
  444. if (ServeThreadRunning) {
  445. this->ShutdownSignal.send();
  446. uv_thread_join(&ServeThread);
  447. }
  448. uv_loop_close(&Loop);
  449. Loop.data = nullptr;
  450. }
  451. }
  452. cmServerBase::~cmServerBase()
  453. {
  454. Close();
  455. }
  456. void cmServerBase::AddNewConnection(cmConnection* ownedConnection)
  457. {
  458. {
  459. std::unique_lock<cm::shared_mutex> lock(ConnectionsMutex);
  460. Connections.emplace_back(ownedConnection);
  461. }
  462. ownedConnection->SetServer(this);
  463. }
  464. uv_loop_t* cmServerBase::GetLoop()
  465. {
  466. return &Loop;
  467. }
  468. void cmServerBase::OnDisconnect(cmConnection* pConnection)
  469. {
  470. auto pred = [pConnection](const std::unique_ptr<cmConnection>& m) {
  471. return m.get() == pConnection;
  472. };
  473. {
  474. std::unique_lock<cm::shared_mutex> lock(ConnectionsMutex);
  475. Connections.erase(
  476. std::remove_if(Connections.begin(), Connections.end(), pred),
  477. Connections.end());
  478. }
  479. if (Connections.empty()) {
  480. this->ShutdownSignal.send();
  481. }
  482. }