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 "cmWorkerPool.h"
7 #include <condition_variable>
19 #include "cmStringAlgorithms.h"
20 #include "cmUVHandlePtr.h"
21 #include "cmUVSignalHackRAII.h" // IWYU pragma: keep
24 * @brief libuv pipe buffer class
29 using DataRange = cmRange<const char*>;
30 using DataFunction = std::function<void(DataRange)>;
31 /// On error the ssize_t argument is a non zero libuv error code
32 using EndFunction = std::function<void(ssize_t)>;
35 * Reset to construction state
40 * Initializes uv_pipe(), uv_stream() and uv_handle()
41 * @return true on success
43 bool init(uv_loop_t* uv_loop);
47 * @return true on success
49 bool startRead(DataFunction dataFunction, EndFunction endFunction);
52 uv_pipe_t* uv_pipe() const { return this->UVPipe_.get(); }
53 //! uv_pipe() casted to libuv stream
54 uv_stream_t* uv_stream() const
56 return static_cast<uv_stream_t*>(this->UVPipe_);
58 //! uv_pipe() casted to libuv handle
59 uv_handle_t* uv_handle() { return static_cast<uv_handle_t*>(this->UVPipe_); }
63 static void UVAlloc(uv_handle_t* handle, size_t suggestedSize,
65 static void UVData(uv_stream_t* stream, ssize_t nread, const uv_buf_t* buf);
67 cm::uv_pipe_ptr UVPipe_;
68 std::vector<char> Buffer_;
69 DataFunction DataFunction_;
70 EndFunction EndFunction_;
73 void cmUVPipeBuffer::reset()
75 if (this->UVPipe_.get() != nullptr) {
76 this->EndFunction_ = nullptr;
77 this->DataFunction_ = nullptr;
78 this->Buffer_.clear();
79 this->Buffer_.shrink_to_fit();
80 this->UVPipe_.reset();
84 bool cmUVPipeBuffer::init(uv_loop_t* uv_loop)
87 if (uv_loop == nullptr) {
90 int ret = this->UVPipe_.init(*uv_loop, 0, this);
94 bool cmUVPipeBuffer::startRead(DataFunction dataFunction,
95 EndFunction endFunction)
97 if (this->UVPipe_.get() == nullptr) {
100 if (!dataFunction || !endFunction) {
103 this->DataFunction_ = std::move(dataFunction);
104 this->EndFunction_ = std::move(endFunction);
105 int ret = uv_read_start(this->uv_stream(), &cmUVPipeBuffer::UVAlloc,
106 &cmUVPipeBuffer::UVData);
110 void cmUVPipeBuffer::UVAlloc(uv_handle_t* handle, size_t suggestedSize,
113 auto& pipe = *reinterpret_cast<cmUVPipeBuffer*>(handle->data);
114 pipe.Buffer_.resize(suggestedSize);
115 buf->base = pipe.Buffer_.data();
116 buf->len = static_cast<unsigned long>(pipe.Buffer_.size());
119 void cmUVPipeBuffer::UVData(uv_stream_t* stream, ssize_t nread,
122 auto& pipe = *reinterpret_cast<cmUVPipeBuffer*>(stream->data);
124 if (buf->base != nullptr) {
125 // Call data function
126 pipe.DataFunction_(DataRange(buf->base, buf->base + nread));
128 } else if (nread < 0) {
129 // Save the end function on the stack before resetting the pipe
131 efunc.swap(pipe.EndFunction_);
132 // Reset pipe before calling the end function
135 efunc((nread == UV_EOF) ? 0 : nread);
140 * @brief External process management class
142 class cmUVReadOnlyProcess
146 //! @brief Process settings
149 std::string WorkingDirectory;
150 std::vector<std::string> Command;
151 cmWorkerPool::ProcessResultT* Result = nullptr;
152 bool MergedOutput = false;
155 // -- Const accessors
156 SetupT const& Setup() const { return this->Setup_; }
157 cmWorkerPool::ProcessResultT* Result() const { return this->Setup_.Result; }
158 bool IsStarted() const { return this->IsStarted_; }
159 bool IsFinished() const { return this->IsFinished_; }
162 void setup(cmWorkerPool::ProcessResultT* result, bool mergedOutput,
163 std::vector<std::string> const& command,
164 std::string const& workingDirectory = std::string());
165 bool start(uv_loop_t* uv_loop, std::function<void()> finishedCallback);
168 // -- Libuv callbacks
169 static void UVExit(uv_process_t* handle, int64_t exitStatus, int termSignal);
170 void UVPipeOutData(cmUVPipeBuffer::DataRange data) const;
171 void UVPipeOutEnd(ssize_t error);
172 void UVPipeErrData(cmUVPipeBuffer::DataRange data) const;
173 void UVPipeErrEnd(ssize_t error);
179 bool IsStarted_ = false;
180 bool IsFinished_ = false;
181 std::function<void()> FinishedCallback_;
182 std::vector<const char*> CommandPtr_;
183 std::array<uv_stdio_container_t, 3> UVOptionsStdIO_;
184 uv_process_options_t UVOptions_;
185 cm::uv_process_ptr UVProcess_;
186 cmUVPipeBuffer UVPipeOut_;
187 cmUVPipeBuffer UVPipeErr_;
190 void cmUVReadOnlyProcess::setup(cmWorkerPool::ProcessResultT* result,
192 std::vector<std::string> const& command,
193 std::string const& workingDirectory)
195 this->Setup_.WorkingDirectory = workingDirectory;
196 this->Setup_.Command = command;
197 this->Setup_.Result = result;
198 this->Setup_.MergedOutput = mergedOutput;
201 bool cmUVReadOnlyProcess::start(uv_loop_t* uv_loop,
202 std::function<void()> finishedCallback)
204 if (this->IsStarted() || (this->Result() == nullptr)) {
208 // Reset result before the start
209 this->Result()->reset();
211 // Fill command string pointers
212 if (!this->Setup().Command.empty()) {
213 this->CommandPtr_.reserve(this->Setup().Command.size() + 1);
214 for (std::string const& arg : this->Setup().Command) {
215 this->CommandPtr_.push_back(arg.c_str());
217 this->CommandPtr_.push_back(nullptr);
219 this->Result()->ErrorMessage = "Empty command";
222 if (!this->Result()->error()) {
223 if (!this->UVPipeOut_.init(uv_loop)) {
224 this->Result()->ErrorMessage = "libuv stdout pipe initialization failed";
227 if (!this->Result()->error()) {
228 if (!this->UVPipeErr_.init(uv_loop)) {
229 this->Result()->ErrorMessage = "libuv stderr pipe initialization failed";
232 if (!this->Result()->error()) {
233 // -- Setup process stdio options
235 this->UVOptionsStdIO_[0].flags = UV_IGNORE;
236 this->UVOptionsStdIO_[0].data.stream = nullptr;
238 this->UVOptionsStdIO_[1].flags =
239 static_cast<uv_stdio_flags>(UV_CREATE_PIPE | UV_WRITABLE_PIPE);
240 this->UVOptionsStdIO_[1].data.stream = this->UVPipeOut_.uv_stream();
242 this->UVOptionsStdIO_[2].flags =
243 static_cast<uv_stdio_flags>(UV_CREATE_PIPE | UV_WRITABLE_PIPE);
244 this->UVOptionsStdIO_[2].data.stream = this->UVPipeErr_.uv_stream();
246 // -- Setup process options
247 std::fill_n(reinterpret_cast<char*>(&this->UVOptions_),
248 sizeof(this->UVOptions_), 0);
249 this->UVOptions_.exit_cb = &cmUVReadOnlyProcess::UVExit;
250 this->UVOptions_.file = this->CommandPtr_[0];
251 this->UVOptions_.args = const_cast<char**>(this->CommandPtr_.data());
252 this->UVOptions_.cwd = this->Setup_.WorkingDirectory.c_str();
253 this->UVOptions_.flags = UV_PROCESS_WINDOWS_HIDE;
254 this->UVOptions_.stdio_count =
255 static_cast<int>(this->UVOptionsStdIO_.size());
256 this->UVOptions_.stdio = this->UVOptionsStdIO_.data();
259 int uvErrorCode = this->UVProcess_.spawn(*uv_loop, this->UVOptions_, this);
260 if (uvErrorCode != 0) {
261 this->Result()->ErrorMessage = "libuv process spawn failed";
262 if (const char* uvErr = uv_strerror(uvErrorCode)) {
263 this->Result()->ErrorMessage += ": ";
264 this->Result()->ErrorMessage += uvErr;
268 // -- Start reading from stdio streams
269 if (!this->Result()->error()) {
270 if (!this->UVPipeOut_.startRead(
271 [this](cmUVPipeBuffer::DataRange range) {
272 this->UVPipeOutData(range);
274 [this](ssize_t error) { this->UVPipeOutEnd(error); })) {
275 this->Result()->ErrorMessage =
276 "libuv start reading from stdout pipe failed";
279 if (!this->Result()->error()) {
280 if (!this->UVPipeErr_.startRead(
281 [this](cmUVPipeBuffer::DataRange range) {
282 this->UVPipeErrData(range);
284 [this](ssize_t error) { this->UVPipeErrEnd(error); })) {
285 this->Result()->ErrorMessage =
286 "libuv start reading from stderr pipe failed";
290 if (!this->Result()->error()) {
291 this->IsStarted_ = true;
292 this->FinishedCallback_ = std::move(finishedCallback);
294 // Clear libuv handles and finish
295 this->UVProcess_.reset();
296 this->UVPipeOut_.reset();
297 this->UVPipeErr_.reset();
298 this->CommandPtr_.clear();
301 return this->IsStarted();
304 void cmUVReadOnlyProcess::UVExit(uv_process_t* handle, int64_t exitStatus,
307 auto& proc = *reinterpret_cast<cmUVReadOnlyProcess*>(handle->data);
308 if (proc.IsStarted() && !proc.IsFinished()) {
309 // Set error message on demand
310 proc.Result()->ExitStatus = exitStatus;
311 proc.Result()->TermSignal = termSignal;
312 if (!proc.Result()->error()) {
313 if (termSignal != 0) {
314 proc.Result()->ErrorMessage = cmStrCat(
315 "Process was terminated by signal ", proc.Result()->TermSignal);
316 } else if (exitStatus != 0) {
317 proc.Result()->ErrorMessage = cmStrCat(
318 "Process failed with return value ", proc.Result()->ExitStatus);
322 // Reset process handle
323 proc.UVProcess_.reset();
329 void cmUVReadOnlyProcess::UVPipeOutData(cmUVPipeBuffer::DataRange data) const
331 this->Result()->StdOut.append(data.begin(), data.end());
334 void cmUVReadOnlyProcess::UVPipeOutEnd(ssize_t error)
336 // Process pipe error
337 if ((error != 0) && !this->Result()->error()) {
338 this->Result()->ErrorMessage = cmStrCat(
339 "Reading from stdout pipe failed with libuv error code ", error);
345 void cmUVReadOnlyProcess::UVPipeErrData(cmUVPipeBuffer::DataRange data) const
347 std::string* str = this->Setup_.MergedOutput ? &this->Result()->StdOut
348 : &this->Result()->StdErr;
349 str->append(data.begin(), data.end());
352 void cmUVReadOnlyProcess::UVPipeErrEnd(ssize_t error)
354 // Process pipe error
355 if ((error != 0) && !this->Result()->error()) {
356 this->Result()->ErrorMessage = cmStrCat(
357 "Reading from stderr pipe failed with libuv error code ", error);
363 void cmUVReadOnlyProcess::UVTryFinish()
365 // There still might be data in the pipes after the process has finished.
366 // Therefore check if the process is finished AND all pipes are closed
367 // before signaling the worker thread to continue.
368 if ((this->UVProcess_.get() != nullptr) ||
369 (this->UVPipeOut_.uv_pipe() != nullptr) ||
370 (this->UVPipeErr_.uv_pipe() != nullptr)) {
373 this->IsFinished_ = true;
374 this->FinishedCallback_();
378 * @brief Worker pool worker thread
380 class cmWorkerPoolWorker
383 cmWorkerPoolWorker(uv_loop_t& uvLoop);
384 ~cmWorkerPoolWorker();
386 cmWorkerPoolWorker(cmWorkerPoolWorker const&) = delete;
387 cmWorkerPoolWorker& operator=(cmWorkerPoolWorker const&) = delete;
390 * Set the internal thread
392 void SetThread(std::thread&& aThread) { this->Thread_ = std::move(aThread); }
395 * Run an external process
397 bool RunProcess(cmWorkerPool::ProcessResultT& result,
398 std::vector<std::string> const& command,
399 std::string const& workingDirectory);
402 // -- Libuv callbacks
403 static void UVProcessStart(uv_async_t* handle);
404 void UVProcessFinished();
406 // -- Process management
410 cm::uv_async_ptr Request;
411 std::condition_variable Condition;
412 std::unique_ptr<cmUVReadOnlyProcess> ROP;
418 cmWorkerPoolWorker::cmWorkerPoolWorker(uv_loop_t& uvLoop)
420 this->Proc_.Request.init(uvLoop, &cmWorkerPoolWorker::UVProcessStart, this);
423 cmWorkerPoolWorker::~cmWorkerPoolWorker()
425 if (this->Thread_.joinable()) {
426 this->Thread_.join();
430 bool cmWorkerPoolWorker::RunProcess(cmWorkerPool::ProcessResultT& result,
431 std::vector<std::string> const& command,
432 std::string const& workingDirectory)
434 if (command.empty()) {
437 // Create process instance
439 std::lock_guard<std::mutex> lock(this->Proc_.Mutex);
440 this->Proc_.ROP = cm::make_unique<cmUVReadOnlyProcess>();
441 this->Proc_.ROP->setup(&result, true, command, workingDirectory);
443 // Send asynchronous process start request to libuv loop
444 this->Proc_.Request.send();
445 // Wait until the process has been finished and destroyed
447 std::unique_lock<std::mutex> ulock(this->Proc_.Mutex);
448 while (this->Proc_.ROP) {
449 this->Proc_.Condition.wait(ulock);
452 return !result.error();
455 void cmWorkerPoolWorker::UVProcessStart(uv_async_t* handle)
457 auto* wrk = reinterpret_cast<cmWorkerPoolWorker*>(handle->data);
458 bool startFailed = false;
460 auto& Proc = wrk->Proc_;
461 std::lock_guard<std::mutex> lock(Proc.Mutex);
462 if (Proc.ROP && !Proc.ROP->IsStarted()) {
464 !Proc.ROP->start(handle->loop, [wrk] { wrk->UVProcessFinished(); });
467 // Clean up if starting of the process failed
469 wrk->UVProcessFinished();
473 void cmWorkerPoolWorker::UVProcessFinished()
475 std::lock_guard<std::mutex> lock(this->Proc_.Mutex);
476 if (this->Proc_.ROP &&
477 (this->Proc_.ROP->IsFinished() || !this->Proc_.ROP->IsStarted())) {
478 this->Proc_.ROP.reset();
480 // Notify idling thread
481 this->Proc_.Condition.notify_one();
485 * @brief Private worker pool internals
487 class cmWorkerPoolInternal
491 cmWorkerPoolInternal(cmWorkerPool* pool);
492 ~cmWorkerPoolInternal();
495 * Runs the libuv loop.
500 * Clear queue and abort threads.
505 * Push a job to the queue and notify a worker.
507 bool PushJob(cmWorkerPool::JobHandleT&& jobHandle);
510 * Worker thread main loop method.
512 void Work(unsigned int workerIndex);
515 static void UVSlotBegin(uv_async_t* handle);
516 static void UVSlotEnd(uv_async_t* handle);
519 #ifdef CMAKE_UV_SIGNAL_HACK
520 std::unique_ptr<cmUVSignalHackRAII> UVHackRAII;
522 std::unique_ptr<uv_loop_t> UVLoop;
523 cm::uv_async_ptr UVRequestBegin;
524 cm::uv_async_ptr UVRequestEnd;
526 // -- Thread pool and job queue
528 bool Processing = false;
529 bool Aborting = false;
530 bool FenceProcessing = false;
531 unsigned int WorkersRunning = 0;
532 unsigned int WorkersIdle = 0;
533 unsigned int JobsProcessing = 0;
534 std::deque<cmWorkerPool::JobHandleT> Queue;
535 std::condition_variable Condition;
536 std::condition_variable ConditionFence;
537 std::vector<std::unique_ptr<cmWorkerPoolWorker>> Workers;
540 cmWorkerPool* Pool = nullptr;
543 void cmWorkerPool::ProcessResultT::reset()
545 this->ExitStatus = 0;
546 this->TermSignal = 0;
547 if (!this->StdOut.empty()) {
548 this->StdOut.clear();
549 this->StdOut.shrink_to_fit();
551 if (!this->StdErr.empty()) {
552 this->StdErr.clear();
553 this->StdErr.shrink_to_fit();
555 if (!this->ErrorMessage.empty()) {
556 this->ErrorMessage.clear();
557 this->ErrorMessage.shrink_to_fit();
561 cmWorkerPoolInternal::cmWorkerPoolInternal(cmWorkerPool* pool)
564 // Initialize libuv loop
565 uv_disable_stdio_inheritance();
566 #ifdef CMAKE_UV_SIGNAL_HACK
567 UVHackRAII = cm::make_unique<cmUVSignalHackRAII>();
569 this->UVLoop = cm::make_unique<uv_loop_t>();
570 uv_loop_init(this->UVLoop.get());
573 cmWorkerPoolInternal::~cmWorkerPoolInternal()
575 uv_loop_close(this->UVLoop.get());
578 bool cmWorkerPoolInternal::Process()
581 this->Processing = true;
582 this->Aborting = false;
583 // Initialize libuv asynchronous request
584 this->UVRequestBegin.init(*this->UVLoop, &cmWorkerPoolInternal::UVSlotBegin,
586 this->UVRequestEnd.init(*this->UVLoop, &cmWorkerPoolInternal::UVSlotEnd,
588 // Send begin request
589 this->UVRequestBegin.send();
591 bool success = (uv_run(this->UVLoop.get(), UV_RUN_DEFAULT) == 0);
592 // Update state flags
593 this->Processing = false;
594 this->Aborting = false;
598 void cmWorkerPoolInternal::Abort()
600 // Clear all jobs and set abort flag
601 std::lock_guard<std::mutex> guard(this->Mutex);
602 if (!this->Aborting) {
603 // Register abort and clear queue
604 this->Aborting = true;
606 this->Condition.notify_all();
610 inline bool cmWorkerPoolInternal::PushJob(cmWorkerPool::JobHandleT&& jobHandle)
612 std::lock_guard<std::mutex> guard(this->Mutex);
613 if (this->Aborting) {
616 // Append the job to the queue
617 this->Queue.emplace_back(std::move(jobHandle));
618 // Notify an idle worker if there's one
619 if (this->WorkersIdle != 0) {
620 this->Condition.notify_one();
626 void cmWorkerPoolInternal::UVSlotBegin(uv_async_t* handle)
628 auto& gint = *reinterpret_cast<cmWorkerPoolInternal*>(handle->data);
629 // Create worker threads
631 unsigned int const num = gint.Pool->ThreadCount();
633 gint.Workers.reserve(num);
634 for (unsigned int ii = 0; ii != num; ++ii) {
635 gint.Workers.emplace_back(
636 cm::make_unique<cmWorkerPoolWorker>(*gint.UVLoop));
638 // Start worker threads
639 for (unsigned int ii = 0; ii != num; ++ii) {
640 gint.Workers[ii]->SetThread(
641 std::thread(&cmWorkerPoolInternal::Work, &gint, ii));
644 // Destroy begin request
645 gint.UVRequestBegin.reset();
648 void cmWorkerPoolInternal::UVSlotEnd(uv_async_t* handle)
650 auto& gint = *reinterpret_cast<cmWorkerPoolInternal*>(handle->data);
651 // Join and destroy worker threads
652 gint.Workers.clear();
653 // Destroy end request
654 gint.UVRequestEnd.reset();
657 void cmWorkerPoolInternal::Work(unsigned int workerIndex)
659 cmWorkerPool::JobHandleT jobHandle;
660 std::unique_lock<std::mutex> uLock(this->Mutex);
661 // Increment running workers count
662 ++this->WorkersRunning;
663 // Enter worker main loop
666 if (this->Aborting) {
669 // Wait for new jobs on the main CV
670 if (this->Queue.empty()) {
672 this->Condition.wait(uLock);
677 // If there is a fence currently active or waiting,
678 // sleep on the main CV and try again.
679 if (this->FenceProcessing) {
680 this->Condition.wait(uLock);
684 // Pop next job from queue
685 jobHandle = std::move(this->Queue.front());
686 this->Queue.pop_front();
688 // Check for fence jobs
689 bool raisedFence = false;
690 if (jobHandle->IsFence()) {
691 this->FenceProcessing = true;
693 // Wait on the Fence CV until all pending jobs are done.
694 while (this->JobsProcessing != 0 && !this->Aborting) {
695 this->ConditionFence.wait(uLock);
697 // When aborting, explicitly kick all threads alive once more.
698 if (this->Aborting) {
699 this->FenceProcessing = false;
700 this->Condition.notify_all();
705 // Unlocked scope for job processing
706 ++this->JobsProcessing;
709 jobHandle->Work(this->Pool, workerIndex); // Process job
710 jobHandle.reset(); // Destroy job
713 --this->JobsProcessing;
715 // If this was the thread that entered fence processing
716 // originally, notify all idling workers that the fence
719 this->FenceProcessing = false;
720 this->Condition.notify_all();
722 // If fence processing is still not done, notify the
723 // the fencing worker when all active jobs are done.
724 if (this->FenceProcessing && this->JobsProcessing == 0) {
725 this->ConditionFence.notify_all();
729 // Decrement running workers count
730 if (--this->WorkersRunning == 0) {
731 // Last worker thread about to finish. Send libuv event.
732 this->UVRequestEnd.send();
736 cmWorkerPool::JobT::~JobT() = default;
738 bool cmWorkerPool::JobT::RunProcess(ProcessResultT& result,
739 std::vector<std::string> const& command,
740 std::string const& workingDirectory)
742 // Get worker by index
743 auto* wrk = this->Pool_->Int_->Workers.at(this->WorkerIndex_).get();
744 return wrk->RunProcess(result, command, workingDirectory);
747 cmWorkerPool::cmWorkerPool()
748 : Int_(cm::make_unique<cmWorkerPoolInternal>(this))
752 cmWorkerPool::~cmWorkerPool() = default;
754 void cmWorkerPool::SetThreadCount(unsigned int threadCount)
756 if (!this->Int_->Processing) {
757 this->ThreadCount_ = (threadCount > 0) ? threadCount : 1u;
761 bool cmWorkerPool::Process(void* userData)
764 this->UserData_ = userData;
766 bool success = this->Int_->Process();
768 this->UserData_ = nullptr;
773 bool cmWorkerPool::PushJob(JobHandleT&& jobHandle)
775 return this->Int_->PushJob(std::move(jobHandle));
778 void cmWorkerPool::Abort()