cmUVJobServerClient.cxx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file LICENSE.rst or https://cmake.org/licensing for details. */
  3. #include "cmUVJobServerClient.h"
  4. #include <cassert>
  5. #include <utility>
  6. #ifndef _WIN32
  7. # include <cstdio>
  8. # include <string>
  9. # include <vector>
  10. # include <fcntl.h>
  11. # include <unistd.h>
  12. # include <sys/types.h>
  13. #endif
  14. #include <cm/memory>
  15. #include <cm/optional>
  16. #include <cm/string_view>
  17. #include "cmRange.h"
  18. #include "cmStringAlgorithms.h"
  19. #include "cmSystemTools.h"
  20. #include "cmUVHandlePtr.h"
  21. class cmUVJobServerClient::Impl
  22. {
  23. public:
  24. uv_loop_t& Loop;
  25. cm::uv_idle_ptr ImplicitToken;
  26. std::function<void()> OnToken;
  27. std::function<void(int)> OnDisconnect;
  28. // The number of tokens held by this client.
  29. unsigned int HeldTokens = 0;
  30. // The number of tokens we need to receive from the job server.
  31. unsigned int NeedTokens = 0;
  32. Impl(uv_loop_t& loop);
  33. virtual ~Impl();
  34. virtual void SendToken() = 0;
  35. virtual void StartReceivingTokens() = 0;
  36. virtual void StopReceivingTokens() = 0;
  37. void RequestToken();
  38. void ReleaseToken();
  39. void RequestExplicitToken();
  40. void DecrementNeedTokens();
  41. void HoldToken();
  42. void RequestImplicitToken();
  43. void ReleaseImplicitToken();
  44. void ReceivedToken();
  45. void Disconnected(int status);
  46. };
  47. cmUVJobServerClient::Impl::Impl(uv_loop_t& loop)
  48. : Loop(loop)
  49. {
  50. this->ImplicitToken.init(this->Loop, this);
  51. }
  52. cmUVJobServerClient::Impl::~Impl() = default;
  53. void cmUVJobServerClient::Impl::RequestToken()
  54. {
  55. if (this->HeldTokens == 0 && !uv_is_active(this->ImplicitToken)) {
  56. this->RequestImplicitToken();
  57. } else {
  58. this->RequestExplicitToken();
  59. }
  60. }
  61. void cmUVJobServerClient::Impl::ReleaseToken()
  62. {
  63. assert(this->HeldTokens > 0);
  64. --this->HeldTokens;
  65. if (this->HeldTokens == 0) {
  66. // This was the token implicitly owned by our process.
  67. this->ReleaseImplicitToken();
  68. } else {
  69. // This was a token we received from the job server. Send it back.
  70. this->SendToken();
  71. }
  72. }
  73. void cmUVJobServerClient::Impl::RequestExplicitToken()
  74. {
  75. ++this->NeedTokens;
  76. this->StartReceivingTokens();
  77. }
  78. void cmUVJobServerClient::Impl::DecrementNeedTokens()
  79. {
  80. assert(this->NeedTokens > 0);
  81. --this->NeedTokens;
  82. if (this->NeedTokens == 0) {
  83. this->StopReceivingTokens();
  84. }
  85. }
  86. void cmUVJobServerClient::Impl::HoldToken()
  87. {
  88. ++this->HeldTokens;
  89. if (this->OnToken) {
  90. this->OnToken();
  91. } else {
  92. this->ReleaseToken();
  93. }
  94. }
  95. void cmUVJobServerClient::Impl::RequestImplicitToken()
  96. {
  97. assert(this->HeldTokens == 0);
  98. this->ImplicitToken.start([](uv_idle_t* handle) {
  99. uv_idle_stop(handle);
  100. auto* self = static_cast<Impl*>(handle->data);
  101. self->HoldToken();
  102. });
  103. }
  104. void cmUVJobServerClient::Impl::ReleaseImplicitToken()
  105. {
  106. assert(this->HeldTokens == 0);
  107. // Use the implicit token in place of receiving one from the job server.
  108. if (this->NeedTokens > 0) {
  109. this->DecrementNeedTokens();
  110. this->RequestImplicitToken();
  111. }
  112. }
  113. void cmUVJobServerClient::Impl::ReceivedToken()
  114. {
  115. this->DecrementNeedTokens();
  116. this->HoldToken();
  117. }
  118. void cmUVJobServerClient::Impl::Disconnected(int status)
  119. {
  120. if (this->OnDisconnect) {
  121. this->OnDisconnect(status);
  122. }
  123. }
  124. //---------------------------------------------------------------------------
  125. // Implementation on POSIX platforms.
  126. // https://www.gnu.org/software/make/manual/html_node/POSIX-Jobserver.html
  127. #ifndef _WIN32
  128. namespace {
  129. class ImplPosix : public cmUVJobServerClient::Impl
  130. {
  131. public:
  132. enum class Connection
  133. {
  134. None,
  135. FDs,
  136. FIFO,
  137. };
  138. Connection Conn = Connection::None;
  139. cm::uv_pipe_ptr ConnRead;
  140. cm::uv_pipe_ptr ConnWrite;
  141. cm::uv_pipe_ptr ConnFIFO;
  142. std::shared_ptr<std::function<void(int)>> OnWrite;
  143. void Connect();
  144. void ConnectFDs(int rfd, int wfd);
  145. void ConnectFIFO(char const* path);
  146. void Disconnect(int status);
  147. cm::uv_pipe_ptr OpenFD(int fd);
  148. uv_stream_t* GetWriter() const;
  149. uv_stream_t* GetReader() const;
  150. static void OnAllocateCB(uv_handle_t* handle, size_t suggested_size,
  151. uv_buf_t* buf);
  152. static void OnReadCB(uv_stream_t* stream, ssize_t nread,
  153. uv_buf_t const* buf);
  154. void OnAllocate(size_t suggested_size, uv_buf_t* buf);
  155. void OnRead(ssize_t nread, uv_buf_t const* buf);
  156. char ReadBuf = '.';
  157. bool ReceivingTokens = false;
  158. bool IsConnected() const;
  159. void SendToken() override;
  160. void StartReceivingTokens() override;
  161. void StopReceivingTokens() override;
  162. ImplPosix(uv_loop_t& loop);
  163. ~ImplPosix() override;
  164. };
  165. ImplPosix::ImplPosix(uv_loop_t& loop)
  166. : Impl(loop)
  167. , OnWrite(std::make_shared<std::function<void(int)>>([this](int status) {
  168. if (status != 0) {
  169. this->Disconnect(status);
  170. }
  171. }))
  172. {
  173. this->Connect();
  174. }
  175. ImplPosix::~ImplPosix()
  176. {
  177. this->Disconnect(0);
  178. }
  179. void ImplPosix::Connect()
  180. {
  181. // --jobserver-auth= for gnu make versions >= 4.2
  182. // --jobserver-fds= for gnu make versions < 4.2
  183. // -J for bsd make
  184. static std::vector<cm::string_view> const prefixes = {
  185. "--jobserver-auth=", "--jobserver-fds=", "-J"
  186. };
  187. cm::optional<std::string> makeflags = cmSystemTools::GetEnvVar("MAKEFLAGS");
  188. if (!makeflags) {
  189. return;
  190. }
  191. // Look for the *last* occurrence of jobserver flags.
  192. cm::optional<std::string> auth;
  193. std::vector<std::string> args;
  194. cmSystemTools::ParseUnixCommandLine(makeflags->c_str(), args);
  195. for (cm::string_view arg : cmReverseRange(args)) {
  196. for (cm::string_view prefix : prefixes) {
  197. if (cmHasPrefix(arg, prefix)) {
  198. auth = cmTrimWhitespace(arg.substr(prefix.length()));
  199. break;
  200. }
  201. }
  202. if (auth) {
  203. break;
  204. }
  205. }
  206. if (!auth) {
  207. return;
  208. }
  209. // fifo:PATH
  210. if (cmHasLiteralPrefix(*auth, "fifo:")) {
  211. ConnectFIFO(auth->substr(cmStrLen("fifo:")).c_str());
  212. return;
  213. }
  214. // reader,writer
  215. int reader;
  216. int writer;
  217. if (std::sscanf(auth->c_str(), "%d,%d", &reader, &writer) == 2) {
  218. ConnectFDs(reader, writer);
  219. }
  220. }
  221. cm::uv_pipe_ptr ImplPosix::OpenFD(int fd)
  222. {
  223. // Create a CLOEXEC duplicate so `uv_pipe_ptr` can close it
  224. // without closing the original file descriptor, which our
  225. // child processes might want to use too.
  226. cm::uv_pipe_ptr p;
  227. int fd_dup = dup(fd);
  228. if (fd_dup < 0) {
  229. return p;
  230. }
  231. if (fcntl(fd_dup, F_SETFD, FD_CLOEXEC) == -1) {
  232. close(fd_dup);
  233. return p;
  234. }
  235. p.init(this->Loop, 0, this);
  236. if (uv_pipe_open(p, fd_dup) < 0) {
  237. close(fd_dup);
  238. }
  239. return p;
  240. }
  241. void ImplPosix::ConnectFDs(int rfd, int wfd)
  242. {
  243. cm::uv_pipe_ptr connRead = this->OpenFD(rfd);
  244. cm::uv_pipe_ptr connWrite = this->OpenFD(wfd);
  245. // Verify that the read end is readable and the write end is writable.
  246. if (!connRead || !uv_is_readable(connRead) || //
  247. !connWrite || !uv_is_writable(connWrite)) {
  248. return;
  249. }
  250. this->ConnRead = std::move(connRead);
  251. this->ConnWrite = std::move(connWrite);
  252. this->Conn = Connection::FDs;
  253. }
  254. void ImplPosix::ConnectFIFO(char const* path)
  255. {
  256. int fd = open(path, O_RDWR);
  257. if (fd < 0) {
  258. return;
  259. }
  260. if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) {
  261. close(fd);
  262. return;
  263. }
  264. cm::uv_pipe_ptr connFIFO;
  265. connFIFO.init(this->Loop, 0, this);
  266. if (uv_pipe_open(connFIFO, fd) != 0) {
  267. close(fd);
  268. return;
  269. }
  270. // Verify that the fifo is both readable and writable.
  271. if (!connFIFO || !uv_is_readable(connFIFO) || !uv_is_writable(connFIFO)) {
  272. return;
  273. }
  274. this->ConnFIFO = std::move(connFIFO);
  275. this->Conn = Connection::FIFO;
  276. }
  277. void ImplPosix::Disconnect(int status)
  278. {
  279. if (this->Conn == Connection::None) {
  280. return;
  281. }
  282. this->StopReceivingTokens();
  283. switch (this->Conn) {
  284. case Connection::FDs:
  285. this->ConnRead.reset();
  286. this->ConnWrite.reset();
  287. break;
  288. case Connection::FIFO:
  289. this->ConnFIFO.reset();
  290. break;
  291. default:
  292. break;
  293. }
  294. this->Conn = Connection::None;
  295. if (status != 0) {
  296. this->Disconnected(status);
  297. }
  298. }
  299. uv_stream_t* ImplPosix::GetWriter() const
  300. {
  301. switch (this->Conn) {
  302. case Connection::FDs:
  303. return this->ConnWrite;
  304. case Connection::FIFO:
  305. return this->ConnFIFO;
  306. default:
  307. return nullptr;
  308. }
  309. }
  310. uv_stream_t* ImplPosix::GetReader() const
  311. {
  312. switch (this->Conn) {
  313. case Connection::FDs:
  314. return this->ConnRead;
  315. case Connection::FIFO:
  316. return this->ConnFIFO;
  317. default:
  318. return nullptr;
  319. }
  320. }
  321. void ImplPosix::OnAllocateCB(uv_handle_t* handle, size_t suggested_size,
  322. uv_buf_t* buf)
  323. {
  324. auto* self = static_cast<ImplPosix*>(handle->data);
  325. self->OnAllocate(suggested_size, buf);
  326. }
  327. void ImplPosix::OnReadCB(uv_stream_t* stream, ssize_t nread,
  328. uv_buf_t const* buf)
  329. {
  330. auto* self = static_cast<ImplPosix*>(stream->data);
  331. self->OnRead(nread, buf);
  332. }
  333. void ImplPosix::OnAllocate(size_t /*suggested_size*/, uv_buf_t* buf)
  334. {
  335. *buf = uv_buf_init(&this->ReadBuf, 1);
  336. }
  337. void ImplPosix::OnRead(ssize_t nread, uv_buf_t const* /*buf*/)
  338. {
  339. if (nread == 0) {
  340. return;
  341. }
  342. if (nread < 0) {
  343. auto status = static_cast<int>(nread);
  344. this->Disconnect(status);
  345. return;
  346. }
  347. assert(nread == 1);
  348. this->ReceivedToken();
  349. }
  350. bool ImplPosix::IsConnected() const
  351. {
  352. return this->Conn != Connection::None;
  353. }
  354. void ImplPosix::SendToken()
  355. {
  356. if (this->Conn == Connection::None) {
  357. return;
  358. }
  359. static char token = '.';
  360. uv_buf_t const buf = uv_buf_init(&token, sizeof(token));
  361. int status = cm::uv_write(this->GetWriter(), &buf, 1, this->OnWrite);
  362. if (status != 0) {
  363. this->Disconnect(status);
  364. }
  365. }
  366. void ImplPosix::StartReceivingTokens()
  367. {
  368. if (this->Conn == Connection::None) {
  369. return;
  370. }
  371. if (this->ReceivingTokens) {
  372. return;
  373. }
  374. int status = uv_read_start(this->GetReader(), &ImplPosix::OnAllocateCB,
  375. &ImplPosix::OnReadCB);
  376. if (status != 0) {
  377. this->Disconnect(status);
  378. return;
  379. }
  380. this->ReceivingTokens = true;
  381. }
  382. void ImplPosix::StopReceivingTokens()
  383. {
  384. if (this->Conn == Connection::None) {
  385. return;
  386. }
  387. if (!this->ReceivingTokens) {
  388. return;
  389. }
  390. this->ReceivingTokens = false;
  391. uv_read_stop(this->GetReader());
  392. }
  393. }
  394. #endif
  395. //---------------------------------------------------------------------------
  396. // Implementation of public interface.
  397. cmUVJobServerClient::cmUVJobServerClient(std::unique_ptr<Impl> impl)
  398. : Impl_(std::move(impl))
  399. {
  400. }
  401. cmUVJobServerClient::~cmUVJobServerClient() = default;
  402. cmUVJobServerClient::cmUVJobServerClient(cmUVJobServerClient&&) noexcept =
  403. default;
  404. cmUVJobServerClient& cmUVJobServerClient::operator=(
  405. cmUVJobServerClient&&) noexcept = default;
  406. void cmUVJobServerClient::RequestToken()
  407. {
  408. this->Impl_->RequestToken();
  409. }
  410. void cmUVJobServerClient::ReleaseToken()
  411. {
  412. this->Impl_->ReleaseToken();
  413. }
  414. int cmUVJobServerClient::GetHeldTokens() const
  415. {
  416. return this->Impl_->HeldTokens;
  417. }
  418. int cmUVJobServerClient::GetNeedTokens() const
  419. {
  420. return this->Impl_->NeedTokens;
  421. }
  422. cm::optional<cmUVJobServerClient> cmUVJobServerClient::Connect(
  423. uv_loop_t& loop, std::function<void()> onToken,
  424. std::function<void(int)> onDisconnect)
  425. {
  426. #if defined(_WIN32)
  427. // FIXME: Windows job server client not yet implemented.
  428. static_cast<void>(loop);
  429. static_cast<void>(onToken);
  430. static_cast<void>(onDisconnect);
  431. #else
  432. auto impl = cm::make_unique<ImplPosix>(loop);
  433. if (impl && impl->IsConnected()) {
  434. impl->OnToken = std::move(onToken);
  435. impl->OnDisconnect = std::move(onDisconnect);
  436. return cmUVJobServerClient(std::move(impl));
  437. }
  438. #endif
  439. return cm::nullopt;
  440. }