blob: df10efd866bccc929aa455d6b1e714dfa43e78aa [file] [log] [blame]
tommic06b1332016-05-14 11:31:40 -07001/*
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 10:44:38 +010011#include "rtc_base/task_queue_libevent.h"
tommic06b1332016-05-14 11:31:40 -070012
Yves Gerey988cc082018-10-23 12:03:01 +020013#include <errno.h>
tommic06b1332016-05-14 11:31:40 -070014#include <fcntl.h>
Yves Gerey988cc082018-10-23 12:03:01 +020015#include <pthread.h>
tommi8c80c6e2017-02-23 00:34:52 -080016#include <signal.h>
Yves Gerey988cc082018-10-23 12:03:01 +020017#include <stdint.h>
18#include <time.h>
tommic06b1332016-05-14 11:31:40 -070019#include <unistd.h>
Jonas Olssona4d87372019-07-05 19:08:33 +020020
Danil Chapovalov02fddf62018-02-12 12:41:16 +010021#include <list>
Yves Gerey988cc082018-10-23 12:03:01 +020022#include <memory>
23#include <type_traits>
24#include <utility>
tommic06b1332016-05-14 11:31:40 -070025
Danil Chapovaloveb175242019-02-12 10:44:38 +010026#include "absl/memory/memory.h"
27#include "absl/strings/string_view.h"
28#include "api/task_queue/queued_task.h"
29#include "api/task_queue/task_queue_base.h"
tommic06b1332016-05-14 11:31:40 -070030#include "base/third_party/libevent/event.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020031#include "rtc_base/checks.h"
Steve Anton10542f22019-01-11 09:11:00 -080032#include "rtc_base/critical_section.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020033#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010034#include "rtc_base/numerics/safe_conversions.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020035#include "rtc_base/platform_thread.h"
Yves Gerey988cc082018-10-23 12:03:01 +020036#include "rtc_base/platform_thread_types.h"
Yves Gerey988cc082018-10-23 12:03:01 +020037#include "rtc_base/thread_annotations.h"
Steve Anton10542f22019-01-11 09:11:00 -080038#include "rtc_base/time_utils.h"
tommic06b1332016-05-14 11:31:40 -070039
Danil Chapovaloveb175242019-02-12 10:44:38 +010040namespace webrtc {
tommic06b1332016-05-14 11:31:40 -070041namespace {
Danil Chapovaloveb175242019-02-12 10:44:38 +010042constexpr char kQuit = 1;
43constexpr char kRunTask = 2;
tommi8c80c6e2017-02-23 00:34:52 -080044
Danil Chapovaloveb175242019-02-12 10:44:38 +010045using Priority = TaskQueueFactory::Priority;
tommic9bb7912017-02-24 10:42:14 -080046
tommi8c80c6e2017-02-23 00:34:52 -080047// This ignores the SIGPIPE signal on the calling thread.
48// This signal can be fired when trying to write() to a pipe that's being
49// closed or while closing a pipe that's being written to.
Danil Chapovalov43f39822018-12-05 15:46:58 +010050// We can run into that situation so we ignore this signal and continue as
51// normal.
tommi8c80c6e2017-02-23 00:34:52 -080052// As a side note for this implementation, it would be great if we could safely
53// restore the sigmask, but unfortunately the operation of restoring it, can
54// itself actually cause SIGPIPE to be signaled :-| (e.g. on MacOS)
55// The SIGPIPE signal by default causes the process to be terminated, so we
56// don't want to risk that.
57// An alternative to this approach is to ignore the signal for the whole
58// process:
59// signal(SIGPIPE, SIG_IGN);
60void IgnoreSigPipeSignalOnCurrentThread() {
61 sigset_t sigpipe_mask;
62 sigemptyset(&sigpipe_mask);
63 sigaddset(&sigpipe_mask, SIGPIPE);
64 pthread_sigmask(SIG_BLOCK, &sigpipe_mask, nullptr);
65}
tommic06b1332016-05-14 11:31:40 -070066
tommic06b1332016-05-14 11:31:40 -070067bool SetNonBlocking(int fd) {
68 const int flags = fcntl(fd, F_GETFL);
69 RTC_CHECK(flags != -1);
70 return (flags & O_NONBLOCK) || fcntl(fd, F_SETFL, flags | O_NONBLOCK) != -1;
71}
tommi1666b612016-07-13 10:58:12 -070072
73// TODO(tommi): This is a hack to support two versions of libevent that we're
74// compatible with. The method we really want to call is event_assign(),
75// since event_set() has been marked as deprecated (and doesn't accept
76// passing event_base__ as a parameter). However, the version of libevent
77// that we have in Chromium, doesn't have event_assign(), so we need to call
78// event_set() there.
79void EventAssign(struct event* ev,
80 struct event_base* base,
81 int fd,
82 short events,
83 void (*callback)(int, short, void*),
84 void* arg) {
85#if defined(_EVENT2_EVENT_H_)
86 RTC_CHECK_EQ(0, event_assign(ev, base, fd, events, callback, arg));
87#else
88 event_set(ev, fd, events, callback, arg);
89 RTC_CHECK_EQ(0, event_base_set(base, ev));
90#endif
91}
tommic9bb7912017-02-24 10:42:14 -080092
Danil Chapovaloveb175242019-02-12 10:44:38 +010093rtc::ThreadPriority TaskQueuePriorityToThreadPriority(Priority priority) {
tommic9bb7912017-02-24 10:42:14 -080094 switch (priority) {
95 case Priority::HIGH:
Danil Chapovaloveb175242019-02-12 10:44:38 +010096 return rtc::kRealtimePriority;
tommic9bb7912017-02-24 10:42:14 -080097 case Priority::LOW:
Danil Chapovaloveb175242019-02-12 10:44:38 +010098 return rtc::kLowPriority;
tommic9bb7912017-02-24 10:42:14 -080099 case Priority::NORMAL:
Danil Chapovaloveb175242019-02-12 10:44:38 +0100100 return rtc::kNormalPriority;
tommic9bb7912017-02-24 10:42:14 -0800101 default:
102 RTC_NOTREACHED();
103 break;
104 }
Danil Chapovaloveb175242019-02-12 10:44:38 +0100105 return rtc::kNormalPriority;
tommic9bb7912017-02-24 10:42:14 -0800106}
tommic06b1332016-05-14 11:31:40 -0700107
Danil Chapovaloveb175242019-02-12 10:44:38 +0100108class TaskQueueLibevent final : public TaskQueueBase {
perkj650fdae2017-08-25 05:00:11 -0700109 public:
Danil Chapovaloveb175242019-02-12 10:44:38 +0100110 TaskQueueLibevent(absl::string_view queue_name, rtc::ThreadPriority priority);
perkj650fdae2017-08-25 05:00:11 -0700111
Danil Chapovaloveb175242019-02-12 10:44:38 +0100112 void Delete() override;
113 void PostTask(std::unique_ptr<QueuedTask> task) override;
114 void PostDelayedTask(std::unique_ptr<QueuedTask> task,
115 uint32_t milliseconds) override;
perkj650fdae2017-08-25 05:00:11 -0700116
117 private:
Danil Chapovaloveb175242019-02-12 10:44:38 +0100118 class SetTimerTask;
119 struct TimerEvent;
120
121 ~TaskQueueLibevent() override = default;
122
perkj650fdae2017-08-25 05:00:11 -0700123 static void ThreadMain(void* context);
124 static void OnWakeup(int socket, short flags, void* context); // NOLINT
perkj650fdae2017-08-25 05:00:11 -0700125 static void RunTimer(int fd, short flags, void* context); // NOLINT
126
Danil Chapovaloveb175242019-02-12 10:44:38 +0100127 bool is_active_ = true;
perkj650fdae2017-08-25 05:00:11 -0700128 int wakeup_pipe_in_ = -1;
129 int wakeup_pipe_out_ = -1;
130 event_base* event_base_;
Danil Chapovaloveb175242019-02-12 10:44:38 +0100131 event wakeup_event_;
132 rtc::PlatformThread thread_;
perkj650fdae2017-08-25 05:00:11 -0700133 rtc::CriticalSection pending_lock_;
danilchap3c6abd22017-09-06 05:46:29 -0700134 std::list<std::unique_ptr<QueuedTask>> pending_ RTC_GUARDED_BY(pending_lock_);
tommic06b1332016-05-14 11:31:40 -0700135 // 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 10:44:38 +0100139struct 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 11:31:40 -0700150 public:
151 SetTimerTask(std::unique_ptr<QueuedTask> task, uint32_t milliseconds)
152 : task_(std::move(task)),
153 milliseconds_(milliseconds),
Danil Chapovaloveb175242019-02-12 10:44:38 +0100154 posted_(rtc::Time32()) {}
tommic06b1332016-05-14 11:31:40 -0700155
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 10:44:38 +0100160 uint32_t post_time = rtc::Time32() - posted_;
161 TaskQueueLibevent::Current()->PostDelayedTask(
tommic06b1332016-05-14 11:31:40 -0700162 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 10:44:38 +0100172TaskQueueLibevent::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 11:31:40 -0700176 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 00:34:52 -0800182
Danil Chapovaloveb175242019-02-12 10:44:38 +0100183 EventAssign(&wakeup_event_, event_base_, wakeup_pipe_out_,
tommi1666b612016-07-13 10:58:12 -0700184 EV_READ | EV_PERSIST, OnWakeup, this);
Danil Chapovaloveb175242019-02-12 10:44:38 +0100185 event_add(&wakeup_event_, 0);
tommic06b1332016-05-14 11:31:40 -0700186 thread_.Start();
187}
188
Danil Chapovaloveb175242019-02-12 10:44:38 +0100189void TaskQueueLibevent::Delete() {
tommic06b1332016-05-14 11:31:40 -0700190 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 10:44:38 +0100203 event_del(&wakeup_event_);
tommi8c80c6e2017-02-23 00:34:52 -0800204
205 IgnoreSigPipeSignalOnCurrentThread();
206
tommic06b1332016-05-14 11:31:40 -0700207 close(wakeup_pipe_in_);
208 close(wakeup_pipe_out_);
209 wakeup_pipe_in_ = -1;
210 wakeup_pipe_out_ = -1;
211
tommic06b1332016-05-14 11:31:40 -0700212 event_base_free(event_base_);
Danil Chapovaloveb175242019-02-12 10:44:38 +0100213 delete this;
tommic06b1332016-05-14 11:31:40 -0700214}
215
Danil Chapovaloveb175242019-02-12 10:44:38 +0100216void TaskQueueLibevent::PostTask(std::unique_ptr<QueuedTask> task) {
Danil Chapovalov00e71ef2019-06-11 18:01:56 +0200217 QueuedTask* task_id = task.get(); // Only used for comparison.
218 {
219 rtc::CritScope lock(&pending_lock_);
220 pending_.push_back(std::move(task));
221 }
222 char message = kRunTask;
223 if (write(wakeup_pipe_in_, &message, sizeof(message)) != sizeof(message)) {
224 RTC_LOG(WARNING) << "Failed to queue task.";
225 rtc::CritScope lock(&pending_lock_);
226 pending_.remove_if([task_id](std::unique_ptr<QueuedTask>& t) {
227 return t.get() == task_id;
228 });
tommic06b1332016-05-14 11:31:40 -0700229 }
230}
231
Danil Chapovaloveb175242019-02-12 10:44:38 +0100232void TaskQueueLibevent::PostDelayedTask(std::unique_ptr<QueuedTask> task,
233 uint32_t milliseconds) {
tommic06b1332016-05-14 11:31:40 -0700234 if (IsCurrent()) {
Danil Chapovaloveb175242019-02-12 10:44:38 +0100235 TimerEvent* timer = new TimerEvent(this, std::move(task));
236 EventAssign(&timer->ev, event_base_, -1, 0, &TaskQueueLibevent::RunTimer,
perkj650fdae2017-08-25 05:00:11 -0700237 timer);
Danil Chapovaloveb175242019-02-12 10:44:38 +0100238 pending_timers_.push_back(timer);
kwiberg5b9746e2017-08-16 04:52:35 -0700239 timeval tv = {rtc::dchecked_cast<int>(milliseconds / 1000),
240 rtc::dchecked_cast<int>(milliseconds % 1000) * 1000};
tommic06b1332016-05-14 11:31:40 -0700241 event_add(&timer->ev, &tv);
242 } else {
Danil Chapovaloveb175242019-02-12 10:44:38 +0100243 PostTask(absl::make_unique<SetTimerTask>(std::move(task), milliseconds));
tommic06b1332016-05-14 11:31:40 -0700244 }
245}
246
tommic06b1332016-05-14 11:31:40 -0700247// static
Danil Chapovaloveb175242019-02-12 10:44:38 +0100248void TaskQueueLibevent::ThreadMain(void* context) {
249 TaskQueueLibevent* me = static_cast<TaskQueueLibevent*>(context);
tommic06b1332016-05-14 11:31:40 -0700250
Danil Chapovaloveb175242019-02-12 10:44:38 +0100251 {
252 CurrentTaskQueueSetter set_current(me);
253 while (me->is_active_)
254 event_base_loop(me->event_base_, 0);
255 }
tommic06b1332016-05-14 11:31:40 -0700256
Danil Chapovaloveb175242019-02-12 10:44:38 +0100257 for (TimerEvent* timer : me->pending_timers_)
tommic06b1332016-05-14 11:31:40 -0700258 delete timer;
tommic06b1332016-05-14 11:31:40 -0700259}
260
261// static
Danil Chapovaloveb175242019-02-12 10:44:38 +0100262void TaskQueueLibevent::OnWakeup(int socket,
263 short flags, // NOLINT
264 void* context) {
265 TaskQueueLibevent* me = static_cast<TaskQueueLibevent*>(context);
266 RTC_DCHECK(me->wakeup_pipe_out_ == socket);
tommic06b1332016-05-14 11:31:40 -0700267 char buf;
268 RTC_CHECK(sizeof(buf) == read(socket, &buf, sizeof(buf)));
269 switch (buf) {
270 case kQuit:
Danil Chapovaloveb175242019-02-12 10:44:38 +0100271 me->is_active_ = false;
272 event_base_loopbreak(me->event_base_);
tommic06b1332016-05-14 11:31:40 -0700273 break;
274 case kRunTask: {
275 std::unique_ptr<QueuedTask> task;
276 {
Danil Chapovaloveb175242019-02-12 10:44:38 +0100277 rtc::CritScope lock(&me->pending_lock_);
278 RTC_DCHECK(!me->pending_.empty());
279 task = std::move(me->pending_.front());
280 me->pending_.pop_front();
tommic06b1332016-05-14 11:31:40 -0700281 RTC_DCHECK(task.get());
282 }
283 if (!task->Run())
284 task.release();
285 break;
286 }
287 default:
288 RTC_NOTREACHED();
289 break;
290 }
291}
292
293// static
Danil Chapovaloveb175242019-02-12 10:44:38 +0100294void TaskQueueLibevent::RunTimer(int fd,
295 short flags, // NOLINT
296 void* context) {
tommic06b1332016-05-14 11:31:40 -0700297 TimerEvent* timer = static_cast<TimerEvent*>(context);
298 if (!timer->task->Run())
299 timer->task.release();
Danil Chapovaloveb175242019-02-12 10:44:38 +0100300 timer->task_queue->pending_timers_.remove(timer);
tommic06b1332016-05-14 11:31:40 -0700301 delete timer;
302}
303
Danil Chapovaloveb175242019-02-12 10:44:38 +0100304class TaskQueueLibeventFactory final : public TaskQueueFactory {
305 public:
306 std::unique_ptr<TaskQueueBase, TaskQueueDeleter> CreateTaskQueue(
307 absl::string_view name,
308 Priority priority) const override {
309 return std::unique_ptr<TaskQueueBase, TaskQueueDeleter>(
310 new TaskQueueLibevent(name,
311 TaskQueuePriorityToThreadPriority(priority)));
312 }
313};
314
315} // namespace
316
317std::unique_ptr<TaskQueueFactory> CreateTaskQueueLibeventFactory() {
318 return absl::make_unique<TaskQueueLibeventFactory>();
perkj650fdae2017-08-25 05:00:11 -0700319}
320
Danil Chapovaloveb175242019-02-12 10:44:38 +0100321} // namespace webrtc