You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

320 lines
9.8 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * Copyright 2016 The WebRTC Project Authors. All rights reserved.
  3. *
  4. * Use of this source code is governed by a BSD-style license
  5. * that can be found in the LICENSE file in the root of the source
  6. * tree. An additional intellectual property rights grant can be found
  7. * in the file PATENTS. All contributing project authors may
  8. * be found in the AUTHORS file in the root of the source tree.
  9. */
  10. #include "rtc_base/task_queue_libevent.h"
  11. #include <errno.h>
  12. #include <fcntl.h>
  13. #include <pthread.h>
  14. #include <signal.h>
  15. #include <stdint.h>
  16. #include <time.h>
  17. #include <unistd.h>
  18. #include <list>
  19. #include <memory>
  20. #include <type_traits>
  21. #include <utility>
  22. #include "absl/strings/string_view.h"
  23. #include "api/task_queue/queued_task.h"
  24. #include "api/task_queue/task_queue_base.h"
  25. #include "base/third_party/libevent/event.h"
  26. #include "rtc_base/checks.h"
  27. #include "rtc_base/critical_section.h"
  28. #include "rtc_base/logging.h"
  29. #include "rtc_base/numerics/safe_conversions.h"
  30. #include "rtc_base/platform_thread.h"
  31. #include "rtc_base/platform_thread_types.h"
  32. #include "rtc_base/thread_annotations.h"
  33. #include "rtc_base/time_utils.h"
  34. namespace webrtc {
  35. namespace {
  36. constexpr char kQuit = 1;
  37. constexpr char kRunTask = 2;
  38. using Priority = TaskQueueFactory::Priority;
  39. // This ignores the SIGPIPE signal on the calling thread.
  40. // This signal can be fired when trying to write() to a pipe that's being
  41. // closed or while closing a pipe that's being written to.
  42. // We can run into that situation so we ignore this signal and continue as
  43. // normal.
  44. // As a side note for this implementation, it would be great if we could safely
  45. // restore the sigmask, but unfortunately the operation of restoring it, can
  46. // itself actually cause SIGPIPE to be signaled :-| (e.g. on MacOS)
  47. // The SIGPIPE signal by default causes the process to be terminated, so we
  48. // don't want to risk that.
  49. // An alternative to this approach is to ignore the signal for the whole
  50. // process:
  51. // signal(SIGPIPE, SIG_IGN);
  52. void IgnoreSigPipeSignalOnCurrentThread() {
  53. sigset_t sigpipe_mask;
  54. sigemptyset(&sigpipe_mask);
  55. sigaddset(&sigpipe_mask, SIGPIPE);
  56. pthread_sigmask(SIG_BLOCK, &sigpipe_mask, nullptr);
  57. }
  58. bool SetNonBlocking(int fd) {
  59. const int flags = fcntl(fd, F_GETFL);
  60. RTC_CHECK(flags != -1);
  61. return (flags & O_NONBLOCK) || fcntl(fd, F_SETFL, flags | O_NONBLOCK) != -1;
  62. }
  63. // TODO(tommi): This is a hack to support two versions of libevent that we're
  64. // compatible with. The method we really want to call is event_assign(),
  65. // since event_set() has been marked as deprecated (and doesn't accept
  66. // passing event_base__ as a parameter). However, the version of libevent
  67. // that we have in Chromium, doesn't have event_assign(), so we need to call
  68. // event_set() there.
  69. void EventAssign(struct event* ev,
  70. struct event_base* base,
  71. int fd,
  72. short events,
  73. void (*callback)(int, short, void*),
  74. void* arg) {
  75. #if defined(_EVENT2_EVENT_H_)
  76. RTC_CHECK_EQ(0, event_assign(ev, base, fd, events, callback, arg));
  77. #else
  78. event_set(ev, fd, events, callback, arg);
  79. RTC_CHECK_EQ(0, event_base_set(base, ev));
  80. #endif
  81. }
  82. rtc::ThreadPriority TaskQueuePriorityToThreadPriority(Priority priority) {
  83. switch (priority) {
  84. case Priority::HIGH:
  85. return rtc::kRealtimePriority;
  86. case Priority::LOW:
  87. return rtc::kLowPriority;
  88. case Priority::NORMAL:
  89. return rtc::kNormalPriority;
  90. default:
  91. RTC_NOTREACHED();
  92. break;
  93. }
  94. return rtc::kNormalPriority;
  95. }
  96. class TaskQueueLibevent final : public TaskQueueBase {
  97. public:
  98. TaskQueueLibevent(absl::string_view queue_name, rtc::ThreadPriority priority);
  99. void Delete() override;
  100. void PostTask(std::unique_ptr<QueuedTask> task) override;
  101. void PostDelayedTask(std::unique_ptr<QueuedTask> task,
  102. uint32_t milliseconds) override;
  103. private:
  104. class SetTimerTask;
  105. struct TimerEvent;
  106. ~TaskQueueLibevent() override = default;
  107. static void ThreadMain(void* context);
  108. static void OnWakeup(int socket, short flags, void* context); // NOLINT
  109. static void RunTimer(int fd, short flags, void* context); // NOLINT
  110. bool is_active_ = true;
  111. int wakeup_pipe_in_ = -1;
  112. int wakeup_pipe_out_ = -1;
  113. event_base* event_base_;
  114. event wakeup_event_;
  115. rtc::PlatformThread thread_;
  116. rtc::CriticalSection pending_lock_;
  117. std::list<std::unique_ptr<QueuedTask>> pending_ RTC_GUARDED_BY(pending_lock_);
  118. // Holds a list of events pending timers for cleanup when the loop exits.
  119. std::list<TimerEvent*> pending_timers_;
  120. };
  121. struct TaskQueueLibevent::TimerEvent {
  122. TimerEvent(TaskQueueLibevent* task_queue, std::unique_ptr<QueuedTask> task)
  123. : task_queue(task_queue), task(std::move(task)) {}
  124. ~TimerEvent() { event_del(&ev); }
  125. event ev;
  126. TaskQueueLibevent* task_queue;
  127. std::unique_ptr<QueuedTask> task;
  128. };
  129. class TaskQueueLibevent::SetTimerTask : public QueuedTask {
  130. public:
  131. SetTimerTask(std::unique_ptr<QueuedTask> task, uint32_t milliseconds)
  132. : task_(std::move(task)),
  133. milliseconds_(milliseconds),
  134. posted_(rtc::Time32()) {}
  135. private:
  136. bool Run() override {
  137. // Compensate for the time that has passed since construction
  138. // and until we got here.
  139. uint32_t post_time = rtc::Time32() - posted_;
  140. TaskQueueLibevent::Current()->PostDelayedTask(
  141. std::move(task_),
  142. post_time > milliseconds_ ? 0 : milliseconds_ - post_time);
  143. return true;
  144. }
  145. std::unique_ptr<QueuedTask> task_;
  146. const uint32_t milliseconds_;
  147. const uint32_t posted_;
  148. };
  149. TaskQueueLibevent::TaskQueueLibevent(absl::string_view queue_name,
  150. rtc::ThreadPriority priority)
  151. : event_base_(event_base_new()),
  152. thread_(&TaskQueueLibevent::ThreadMain, this, queue_name, priority) {
  153. int fds[2];
  154. RTC_CHECK(pipe(fds) == 0);
  155. SetNonBlocking(fds[0]);
  156. SetNonBlocking(fds[1]);
  157. wakeup_pipe_out_ = fds[0];
  158. wakeup_pipe_in_ = fds[1];
  159. EventAssign(&wakeup_event_, event_base_, wakeup_pipe_out_,
  160. EV_READ | EV_PERSIST, OnWakeup, this);
  161. event_add(&wakeup_event_, 0);
  162. thread_.Start();
  163. }
  164. void TaskQueueLibevent::Delete() {
  165. RTC_DCHECK(!IsCurrent());
  166. struct timespec ts;
  167. char message = kQuit;
  168. while (write(wakeup_pipe_in_, &message, sizeof(message)) != sizeof(message)) {
  169. // The queue is full, so we have no choice but to wait and retry.
  170. RTC_CHECK_EQ(EAGAIN, errno);
  171. ts.tv_sec = 0;
  172. ts.tv_nsec = 1000000;
  173. nanosleep(&ts, nullptr);
  174. }
  175. thread_.Stop();
  176. event_del(&wakeup_event_);
  177. IgnoreSigPipeSignalOnCurrentThread();
  178. close(wakeup_pipe_in_);
  179. close(wakeup_pipe_out_);
  180. wakeup_pipe_in_ = -1;
  181. wakeup_pipe_out_ = -1;
  182. event_base_free(event_base_);
  183. delete this;
  184. }
  185. void TaskQueueLibevent::PostTask(std::unique_ptr<QueuedTask> task) {
  186. QueuedTask* task_id = task.get(); // Only used for comparison.
  187. {
  188. rtc::CritScope lock(&pending_lock_);
  189. pending_.push_back(std::move(task));
  190. }
  191. char message = kRunTask;
  192. if (write(wakeup_pipe_in_, &message, sizeof(message)) != sizeof(message)) {
  193. RTC_LOG(WARNING) << "Failed to queue task.";
  194. rtc::CritScope lock(&pending_lock_);
  195. pending_.remove_if([task_id](std::unique_ptr<QueuedTask>& t) {
  196. return t.get() == task_id;
  197. });
  198. }
  199. }
  200. void TaskQueueLibevent::PostDelayedTask(std::unique_ptr<QueuedTask> task,
  201. uint32_t milliseconds) {
  202. if (IsCurrent()) {
  203. TimerEvent* timer = new TimerEvent(this, std::move(task));
  204. EventAssign(&timer->ev, event_base_, -1, 0, &TaskQueueLibevent::RunTimer,
  205. timer);
  206. pending_timers_.push_back(timer);
  207. timeval tv = {rtc::dchecked_cast<int>(milliseconds / 1000),
  208. rtc::dchecked_cast<int>(milliseconds % 1000) * 1000};
  209. event_add(&timer->ev, &tv);
  210. } else {
  211. PostTask(std::make_unique<SetTimerTask>(std::move(task), milliseconds));
  212. }
  213. }
  214. // static
  215. void TaskQueueLibevent::ThreadMain(void* context) {
  216. TaskQueueLibevent* me = static_cast<TaskQueueLibevent*>(context);
  217. {
  218. CurrentTaskQueueSetter set_current(me);
  219. while (me->is_active_)
  220. event_base_loop(me->event_base_, 0);
  221. }
  222. for (TimerEvent* timer : me->pending_timers_)
  223. delete timer;
  224. }
  225. // static
  226. void TaskQueueLibevent::OnWakeup(int socket,
  227. short flags, // NOLINT
  228. void* context) {
  229. TaskQueueLibevent* me = static_cast<TaskQueueLibevent*>(context);
  230. RTC_DCHECK(me->wakeup_pipe_out_ == socket);
  231. char buf;
  232. RTC_CHECK(sizeof(buf) == read(socket, &buf, sizeof(buf)));
  233. switch (buf) {
  234. case kQuit:
  235. me->is_active_ = false;
  236. event_base_loopbreak(me->event_base_);
  237. break;
  238. case kRunTask: {
  239. std::unique_ptr<QueuedTask> task;
  240. {
  241. rtc::CritScope lock(&me->pending_lock_);
  242. RTC_DCHECK(!me->pending_.empty());
  243. task = std::move(me->pending_.front());
  244. me->pending_.pop_front();
  245. RTC_DCHECK(task.get());
  246. }
  247. if (!task->Run())
  248. task.release();
  249. break;
  250. }
  251. default:
  252. RTC_NOTREACHED();
  253. break;
  254. }
  255. }
  256. // static
  257. void TaskQueueLibevent::RunTimer(int fd,
  258. short flags, // NOLINT
  259. void* context) {
  260. TimerEvent* timer = static_cast<TimerEvent*>(context);
  261. if (!timer->task->Run())
  262. timer->task.release();
  263. timer->task_queue->pending_timers_.remove(timer);
  264. delete timer;
  265. }
  266. class TaskQueueLibeventFactory final : public TaskQueueFactory {
  267. public:
  268. std::unique_ptr<TaskQueueBase, TaskQueueDeleter> CreateTaskQueue(
  269. absl::string_view name,
  270. Priority priority) const override {
  271. return std::unique_ptr<TaskQueueBase, TaskQueueDeleter>(
  272. new TaskQueueLibevent(name,
  273. TaskQueuePriorityToThreadPriority(priority)));
  274. }
  275. };
  276. } // namespace
  277. std::unique_ptr<TaskQueueFactory> CreateTaskQueueLibeventFactory() {
  278. return std::make_unique<TaskQueueLibeventFactory>();
  279. }
  280. } // namespace webrtc