blob: 38704c89aeb6c3297270e865195f2572c899283a [file] [log] [blame]
tommic06b1332016-05-14 18:31:401/*
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
Danil Chapovaloveb175242019-02-12 09:44:3811#include "rtc_base/task_queue_libevent.h"
tommic06b1332016-05-14 18:31:4012
Yves Gerey988cc082018-10-23 10:03:0113#include <errno.h>
tommic06b1332016-05-14 18:31:4014#include <fcntl.h>
Yves Gerey988cc082018-10-23 10:03:0115#include <pthread.h>
tommi8c80c6e2017-02-23 08:34:5216#include <signal.h>
Yves Gerey988cc082018-10-23 10:03:0117#include <stdint.h>
18#include <time.h>
tommic06b1332016-05-14 18:31:4019#include <unistd.h>
Danil Chapovalov02fddf62018-02-12 11:41:1620#include <list>
Yves Gerey988cc082018-10-23 10:03:0121#include <memory>
22#include <type_traits>
23#include <utility>
tommic06b1332016-05-14 18:31:4024
Danil Chapovaloveb175242019-02-12 09:44:3825#include "absl/memory/memory.h"
26#include "absl/strings/string_view.h"
27#include "api/task_queue/queued_task.h"
28#include "api/task_queue/task_queue_base.h"
tommic06b1332016-05-14 18:31:4029#include "base/third_party/libevent/event.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3130#include "rtc_base/checks.h"
Steve Anton10542f22019-01-11 17:11:0031#include "rtc_base/critical_section.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3132#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 09:42:2633#include "rtc_base/numerics/safe_conversions.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3134#include "rtc_base/platform_thread.h"
Yves Gerey988cc082018-10-23 10:03:0135#include "rtc_base/platform_thread_types.h"
Yves Gerey988cc082018-10-23 10:03:0136#include "rtc_base/thread_annotations.h"
Steve Anton10542f22019-01-11 17:11:0037#include "rtc_base/time_utils.h"
tommic06b1332016-05-14 18:31:4038
Danil Chapovaloveb175242019-02-12 09:44:3839namespace webrtc {
tommic06b1332016-05-14 18:31:4040namespace {
Danil Chapovaloveb175242019-02-12 09:44:3841constexpr char kQuit = 1;
42constexpr char kRunTask = 2;
tommi8c80c6e2017-02-23 08:34:5243
Danil Chapovaloveb175242019-02-12 09:44:3844using Priority = TaskQueueFactory::Priority;
tommic9bb7912017-02-24 18:42:1445
tommi8c80c6e2017-02-23 08:34:5246// This ignores the SIGPIPE signal on the calling thread.
47// This signal can be fired when trying to write() to a pipe that's being
48// closed or while closing a pipe that's being written to.
Danil Chapovalov43f39822018-12-05 14:46:5849// We can run into that situation so we ignore this signal and continue as
50// normal.
tommi8c80c6e2017-02-23 08:34:5251// As a side note for this implementation, it would be great if we could safely
52// restore the sigmask, but unfortunately the operation of restoring it, can
53// itself actually cause SIGPIPE to be signaled :-| (e.g. on MacOS)
54// The SIGPIPE signal by default causes the process to be terminated, so we
55// don't want to risk that.
56// An alternative to this approach is to ignore the signal for the whole
57// process:
58// signal(SIGPIPE, SIG_IGN);
59void IgnoreSigPipeSignalOnCurrentThread() {
60 sigset_t sigpipe_mask;
61 sigemptyset(&sigpipe_mask);
62 sigaddset(&sigpipe_mask, SIGPIPE);
63 pthread_sigmask(SIG_BLOCK, &sigpipe_mask, nullptr);
64}
tommic06b1332016-05-14 18:31:4065
tommic06b1332016-05-14 18:31:4066bool SetNonBlocking(int fd) {
67 const int flags = fcntl(fd, F_GETFL);
68 RTC_CHECK(flags != -1);
69 return (flags & O_NONBLOCK) || fcntl(fd, F_SETFL, flags | O_NONBLOCK) != -1;
70}
tommi1666b612016-07-13 17:58:1271
72// TODO(tommi): This is a hack to support two versions of libevent that we're
73// compatible with. The method we really want to call is event_assign(),
74// since event_set() has been marked as deprecated (and doesn't accept
75// passing event_base__ as a parameter). However, the version of libevent
76// that we have in Chromium, doesn't have event_assign(), so we need to call
77// event_set() there.
78void EventAssign(struct event* ev,
79 struct event_base* base,
80 int fd,
81 short events,
82 void (*callback)(int, short, void*),
83 void* arg) {
84#if defined(_EVENT2_EVENT_H_)
85 RTC_CHECK_EQ(0, event_assign(ev, base, fd, events, callback, arg));
86#else
87 event_set(ev, fd, events, callback, arg);
88 RTC_CHECK_EQ(0, event_base_set(base, ev));
89#endif
90}
tommic9bb7912017-02-24 18:42:1491
Danil Chapovaloveb175242019-02-12 09:44:3892rtc::ThreadPriority TaskQueuePriorityToThreadPriority(Priority priority) {
tommic9bb7912017-02-24 18:42:1493 switch (priority) {
94 case Priority::HIGH:
Danil Chapovaloveb175242019-02-12 09:44:3895 return rtc::kRealtimePriority;
tommic9bb7912017-02-24 18:42:1496 case Priority::LOW:
Danil Chapovaloveb175242019-02-12 09:44:3897 return rtc::kLowPriority;
tommic9bb7912017-02-24 18:42:1498 case Priority::NORMAL:
Danil Chapovaloveb175242019-02-12 09:44:3899 return rtc::kNormalPriority;
tommic9bb7912017-02-24 18:42:14100 default:
101 RTC_NOTREACHED();
102 break;
103 }
Danil Chapovaloveb175242019-02-12 09:44:38104 return rtc::kNormalPriority;
tommic9bb7912017-02-24 18:42:14105}
tommic06b1332016-05-14 18:31:40106
Danil Chapovaloveb175242019-02-12 09:44:38107class TaskQueueLibevent final : public TaskQueueBase {
perkj650fdae2017-08-25 12:00:11108 public:
Danil Chapovaloveb175242019-02-12 09:44:38109 TaskQueueLibevent(absl::string_view queue_name, rtc::ThreadPriority priority);
perkj650fdae2017-08-25 12:00:11110
Danil Chapovaloveb175242019-02-12 09:44:38111 void Delete() override;
112 void PostTask(std::unique_ptr<QueuedTask> task) override;
113 void PostDelayedTask(std::unique_ptr<QueuedTask> task,
114 uint32_t milliseconds) override;
perkj650fdae2017-08-25 12:00:11115
116 private:
Danil Chapovaloveb175242019-02-12 09:44:38117 class SetTimerTask;
118 struct TimerEvent;
119
120 ~TaskQueueLibevent() override = default;
121
perkj650fdae2017-08-25 12:00:11122 static void ThreadMain(void* context);
123 static void OnWakeup(int socket, short flags, void* context); // NOLINT
124 static void RunTask(int fd, short flags, void* context); // NOLINT
125 static void RunTimer(int fd, short flags, void* context); // NOLINT
126
Danil Chapovaloveb175242019-02-12 09:44:38127 bool is_active_ = true;
perkj650fdae2017-08-25 12:00:11128 int wakeup_pipe_in_ = -1;
129 int wakeup_pipe_out_ = -1;
130 event_base* event_base_;
Danil Chapovaloveb175242019-02-12 09:44:38131 event wakeup_event_;
132 rtc::PlatformThread thread_;
perkj650fdae2017-08-25 12:00:11133 rtc::CriticalSection pending_lock_;
danilchap3c6abd22017-09-06 12:46:29134 std::list<std::unique_ptr<QueuedTask>> pending_ RTC_GUARDED_BY(pending_lock_);
tommic06b1332016-05-14 18:31:40135 // Holds a list of events pending timers for cleanup when the loop exits.
136 std::list<TimerEvent*> pending_timers_;
137};
138
Danil Chapovaloveb175242019-02-12 09:44:38139struct TaskQueueLibevent::TimerEvent {
140 TimerEvent(TaskQueueLibevent* task_queue, std::unique_ptr<QueuedTask> task)
141 : task_queue(task_queue), task(std::move(task)) {}
142 ~TimerEvent() { event_del(&ev); }
143
144 event ev;
145 TaskQueueLibevent* task_queue;
146 std::unique_ptr<QueuedTask> task;
147};
148
149class TaskQueueLibevent::SetTimerTask : public QueuedTask {
tommic06b1332016-05-14 18:31:40150 public:
151 SetTimerTask(std::unique_ptr<QueuedTask> task, uint32_t milliseconds)
152 : task_(std::move(task)),
153 milliseconds_(milliseconds),
Danil Chapovaloveb175242019-02-12 09:44:38154 posted_(rtc::Time32()) {}
tommic06b1332016-05-14 18:31:40155
156 private:
157 bool Run() override {
158 // Compensate for the time that has passed since construction
159 // and until we got here.
Danil Chapovaloveb175242019-02-12 09:44:38160 uint32_t post_time = rtc::Time32() - posted_;
161 TaskQueueLibevent::Current()->PostDelayedTask(
tommic06b1332016-05-14 18:31:40162 std::move(task_),
163 post_time > milliseconds_ ? 0 : milliseconds_ - post_time);
164 return true;
165 }
166
167 std::unique_ptr<QueuedTask> task_;
168 const uint32_t milliseconds_;
169 const uint32_t posted_;
170};
171
Danil Chapovaloveb175242019-02-12 09:44:38172TaskQueueLibevent::TaskQueueLibevent(absl::string_view queue_name,
173 rtc::ThreadPriority priority)
174 : event_base_(event_base_new()),
175 thread_(&TaskQueueLibevent::ThreadMain, this, queue_name, priority) {
tommic06b1332016-05-14 18:31:40176 int fds[2];
177 RTC_CHECK(pipe(fds) == 0);
178 SetNonBlocking(fds[0]);
179 SetNonBlocking(fds[1]);
180 wakeup_pipe_out_ = fds[0];
181 wakeup_pipe_in_ = fds[1];
tommi8c80c6e2017-02-23 08:34:52182
Danil Chapovaloveb175242019-02-12 09:44:38183 EventAssign(&wakeup_event_, event_base_, wakeup_pipe_out_,
tommi1666b612016-07-13 17:58:12184 EV_READ | EV_PERSIST, OnWakeup, this);
Danil Chapovaloveb175242019-02-12 09:44:38185 event_add(&wakeup_event_, 0);
tommic06b1332016-05-14 18:31:40186 thread_.Start();
187}
188
Danil Chapovaloveb175242019-02-12 09:44:38189void TaskQueueLibevent::Delete() {
tommic06b1332016-05-14 18:31:40190 RTC_DCHECK(!IsCurrent());
191 struct timespec ts;
192 char message = kQuit;
193 while (write(wakeup_pipe_in_, &message, sizeof(message)) != sizeof(message)) {
194 // The queue is full, so we have no choice but to wait and retry.
195 RTC_CHECK_EQ(EAGAIN, errno);
196 ts.tv_sec = 0;
197 ts.tv_nsec = 1000000;
198 nanosleep(&ts, nullptr);
199 }
200
201 thread_.Stop();
202
Danil Chapovaloveb175242019-02-12 09:44:38203 event_del(&wakeup_event_);
tommi8c80c6e2017-02-23 08:34:52204
205 IgnoreSigPipeSignalOnCurrentThread();
206
tommic06b1332016-05-14 18:31:40207 close(wakeup_pipe_in_);
208 close(wakeup_pipe_out_);
209 wakeup_pipe_in_ = -1;
210 wakeup_pipe_out_ = -1;
211
tommic06b1332016-05-14 18:31:40212 event_base_free(event_base_);
Danil Chapovaloveb175242019-02-12 09:44:38213 delete this;
tommic06b1332016-05-14 18:31:40214}
215
Danil Chapovaloveb175242019-02-12 09:44:38216void TaskQueueLibevent::PostTask(std::unique_ptr<QueuedTask> task) {
tommic06b1332016-05-14 18:31:40217 RTC_DCHECK(task.get());
218 // libevent isn't thread safe. This means that we can't use methods such
219 // as event_base_once to post tasks to the worker thread from a different
220 // thread. However, we can use it when posting from the worker thread itself.
221 if (IsCurrent()) {
Danil Chapovaloveb175242019-02-12 09:44:38222 if (event_base_once(event_base_, -1, EV_TIMEOUT,
223 &TaskQueueLibevent::RunTask, task.get(),
224 nullptr) == 0) {
tommic06b1332016-05-14 18:31:40225 task.release();
226 }
227 } else {
228 QueuedTask* task_id = task.get(); // Only used for comparison.
229 {
Danil Chapovaloveb175242019-02-12 09:44:38230 rtc::CritScope lock(&pending_lock_);
tommic06b1332016-05-14 18:31:40231 pending_.push_back(std::move(task));
232 }
233 char message = kRunTask;
234 if (write(wakeup_pipe_in_, &message, sizeof(message)) != sizeof(message)) {
Mirko Bonadei675513b2017-11-09 10:09:25235 RTC_LOG(WARNING) << "Failed to queue task.";
Danil Chapovaloveb175242019-02-12 09:44:38236 rtc::CritScope lock(&pending_lock_);
tommic06b1332016-05-14 18:31:40237 pending_.remove_if([task_id](std::unique_ptr<QueuedTask>& t) {
238 return t.get() == task_id;
239 });
240 }
241 }
242}
243
Danil Chapovaloveb175242019-02-12 09:44:38244void TaskQueueLibevent::PostDelayedTask(std::unique_ptr<QueuedTask> task,
245 uint32_t milliseconds) {
tommic06b1332016-05-14 18:31:40246 if (IsCurrent()) {
Danil Chapovaloveb175242019-02-12 09:44:38247 TimerEvent* timer = new TimerEvent(this, std::move(task));
248 EventAssign(&timer->ev, event_base_, -1, 0, &TaskQueueLibevent::RunTimer,
perkj650fdae2017-08-25 12:00:11249 timer);
Danil Chapovaloveb175242019-02-12 09:44:38250 pending_timers_.push_back(timer);
kwiberg5b9746e2017-08-16 11:52:35251 timeval tv = {rtc::dchecked_cast<int>(milliseconds / 1000),
252 rtc::dchecked_cast<int>(milliseconds % 1000) * 1000};
tommic06b1332016-05-14 18:31:40253 event_add(&timer->ev, &tv);
254 } else {
Danil Chapovaloveb175242019-02-12 09:44:38255 PostTask(absl::make_unique<SetTimerTask>(std::move(task), milliseconds));
tommic06b1332016-05-14 18:31:40256 }
257}
258
tommic06b1332016-05-14 18:31:40259// static
Danil Chapovaloveb175242019-02-12 09:44:38260void TaskQueueLibevent::ThreadMain(void* context) {
261 TaskQueueLibevent* me = static_cast<TaskQueueLibevent*>(context);
tommic06b1332016-05-14 18:31:40262
Danil Chapovaloveb175242019-02-12 09:44:38263 {
264 CurrentTaskQueueSetter set_current(me);
265 while (me->is_active_)
266 event_base_loop(me->event_base_, 0);
267 }
tommic06b1332016-05-14 18:31:40268
Danil Chapovaloveb175242019-02-12 09:44:38269 for (TimerEvent* timer : me->pending_timers_)
tommic06b1332016-05-14 18:31:40270 delete timer;
tommic06b1332016-05-14 18:31:40271}
272
273// static
Danil Chapovaloveb175242019-02-12 09:44:38274void TaskQueueLibevent::OnWakeup(int socket,
275 short flags, // NOLINT
276 void* context) {
277 TaskQueueLibevent* me = static_cast<TaskQueueLibevent*>(context);
278 RTC_DCHECK(me->wakeup_pipe_out_ == socket);
tommic06b1332016-05-14 18:31:40279 char buf;
280 RTC_CHECK(sizeof(buf) == read(socket, &buf, sizeof(buf)));
281 switch (buf) {
282 case kQuit:
Danil Chapovaloveb175242019-02-12 09:44:38283 me->is_active_ = false;
284 event_base_loopbreak(me->event_base_);
tommic06b1332016-05-14 18:31:40285 break;
286 case kRunTask: {
287 std::unique_ptr<QueuedTask> task;
288 {
Danil Chapovaloveb175242019-02-12 09:44:38289 rtc::CritScope lock(&me->pending_lock_);
290 RTC_DCHECK(!me->pending_.empty());
291 task = std::move(me->pending_.front());
292 me->pending_.pop_front();
tommic06b1332016-05-14 18:31:40293 RTC_DCHECK(task.get());
294 }
295 if (!task->Run())
296 task.release();
297 break;
298 }
299 default:
300 RTC_NOTREACHED();
301 break;
302 }
303}
304
305// static
Danil Chapovaloveb175242019-02-12 09:44:38306void TaskQueueLibevent::RunTask(int fd, short flags, void* context) { // NOLINT
tommic06b1332016-05-14 18:31:40307 auto* task = static_cast<QueuedTask*>(context);
308 if (task->Run())
309 delete task;
310}
311
312// static
Danil Chapovaloveb175242019-02-12 09:44:38313void TaskQueueLibevent::RunTimer(int fd,
314 short flags, // NOLINT
315 void* context) {
tommic06b1332016-05-14 18:31:40316 TimerEvent* timer = static_cast<TimerEvent*>(context);
317 if (!timer->task->Run())
318 timer->task.release();
Danil Chapovaloveb175242019-02-12 09:44:38319 timer->task_queue->pending_timers_.remove(timer);
tommic06b1332016-05-14 18:31:40320 delete timer;
321}
322
Danil Chapovaloveb175242019-02-12 09:44:38323class TaskQueueLibeventFactory final : public TaskQueueFactory {
324 public:
325 std::unique_ptr<TaskQueueBase, TaskQueueDeleter> CreateTaskQueue(
326 absl::string_view name,
327 Priority priority) const override {
328 return std::unique_ptr<TaskQueueBase, TaskQueueDeleter>(
329 new TaskQueueLibevent(name,
330 TaskQueuePriorityToThreadPriority(priority)));
331 }
332};
333
334} // namespace
335
336std::unique_ptr<TaskQueueFactory> CreateTaskQueueLibeventFactory() {
337 return absl::make_unique<TaskQueueLibeventFactory>();
perkj650fdae2017-08-25 12:00:11338}
339
Danil Chapovaloveb175242019-02-12 09:44:38340} // namespace webrtc