Unverified 提交 6821b55c authored 作者: José Luis Millán's avatar José Luis Millán 提交者: GitHub

liburing (#1218)

Enable liburing usage for linux (kernel versions >= 6).

Use liburing to relay incoming RTP to Consumers. This greately reduces the
number of system calls as just a single system call is needed to relay the
incoming RTP packet to "every" Consumer, opposite to libuv which requires a
system call to relay the RTP packet to "each" Consumer.

For efficiency, memory buffers are preallocated holding the data payload
being sent.

---------
Co-authored-by: 's avatarIñaki Baz Castillo <ibc@aliax.net>
上级 f296e9fa
# Changelog
### NEXT
* Enable `liburing` usage for Linux (kernel versions >= 6) ([PR #1218](https://github.com/versatica/mediasoup/pull/1218)).
### 3.13.6
* Replace make + Makefile with Python Invoke library + tasks.py (also fix installation under path with whitespaces) ([PR #1239](https://github.com/versatica/mediasoup/pull/1239)).
......
......@@ -192,6 +192,12 @@ export type WorkerDump =
channelRequestHandlers : string[];
channelNotificationHandlers : string[];
};
liburing? :
{
sqeProcessCount: number;
sqeMissCount: number;
userDataMissCount: number;
};
};
export type WorkerEvents =
......@@ -814,7 +820,7 @@ export function parseWorkerDumpResponse(
binary: FbsWorker.DumpResponse
): WorkerDump
{
return {
const dump: WorkerDump = {
pid : binary.pid()!,
webRtcServerIds : parseVector(binary, 'webRtcServerIds'),
routerIds : parseVector(binary, 'routerIds'),
......@@ -824,4 +830,16 @@ export function parseWorkerDumpResponse(
channelNotificationHandlers : parseVector(binary.channelMessageHandlers()!, 'channelNotificationHandlers')
}
};
if (binary.liburing())
{
dump.liburing =
{
sqeProcessCount : Number(binary.liburing()!.sqeProcessCount()),
sqeMissCount : Number(binary.liburing()!.sqeMissCount()),
userDataMissCount : Number(binary.liburing()!.userDataMissCount())
};
}
return dump;
}
......@@ -65,7 +65,7 @@ test('worker.createRouter() succeeds', async () =>
await expect(worker.dump())
.resolves
.toEqual(
.toMatchObject(
{
pid : worker.pid,
webRtcServerIds : [],
......
......@@ -46,7 +46,7 @@ test('worker.createWebRtcServer() succeeds', async () =>
await expect(worker.dump())
.resolves
.toEqual(
.toMatchObject(
{
pid : worker.pid,
webRtcServerIds : [ webRtcServer.id ],
......@@ -120,7 +120,7 @@ test('worker.createWebRtcServer() without specifying port succeeds', async () =>
await expect(worker.dump())
.resolves
.toEqual(
.toMatchObject(
{
pid : worker.pid,
webRtcServerIds : [ webRtcServer.id ],
......@@ -565,7 +565,7 @@ test('router.createWebRtcTransport() with webRtcServer succeeds and webRtcServer
await expect(worker.dump())
.resolves
.toEqual(
.toMatchObject(
{
pid : worker.pid,
webRtcServerIds : [],
......
......@@ -135,7 +135,7 @@ test('worker.dump() succeeds', async () =>
await expect(worker.dump())
.resolves
.toEqual(
.toMatchObject(
{
pid : worker.pid,
webRtcServerIds : [],
......
......@@ -29,7 +29,7 @@ use crate::webrtc_server::{
use crate::webrtc_transport::{
WebRtcTransportListen, WebRtcTransportListenInfos, WebRtcTransportOptions,
};
use crate::worker::{ChannelMessageHandlers, WorkerDump, WorkerUpdateSettings};
use crate::worker::{ChannelMessageHandlers, LibUringDump, WorkerDump, WorkerUpdateSettings};
use mediasoup_sys::fbs::{
active_speaker_observer, audio_level_observer, consumer, data_consumer, data_producer,
direct_transport, message, notification, pipe_transport, plain_transport, producer, request,
......@@ -165,6 +165,11 @@ impl Request for WorkerDumpRequest {
.map(|id| id.parse())
.collect::<Result<_, _>>()?,
},
liburing: data.liburing.map(|liburing| LibUringDump {
sqe_process_count: liburing.sqe_process_count,
sqe_miss_count: liburing.sqe_miss_count,
user_data_miss_count: liburing.user_data_miss_count,
}),
})
}
}
......
......@@ -278,6 +278,14 @@ pub struct ChannelMessageHandlers {
pub channel_notification_handlers: Vec<Uuid>,
}
#[derive(Debug, Clone, Deserialize, Serialize, Eq, PartialEq)]
#[doc(hidden)]
pub struct LibUringDump {
pub sqe_process_count: u64,
pub sqe_miss_count: u64,
pub user_data_miss_count: u64,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
#[doc(hidden)]
......@@ -288,6 +296,7 @@ pub struct WorkerDump {
#[serde(rename = "webRtcServerIds")]
pub webrtc_server_ids: Vec<WebRtcServerId>,
pub channel_message_handlers: ChannelMessageHandlers,
pub liburing: Option<LibUringDump>,
}
/// Error that caused [`Worker::create_webrtc_server`] to fail.
......
namespace FBS.LibUring;
table Dump {
sqe_process_count: uint64;
sqe_miss_count: uint64;
user_data_miss_count: uint64;
}
......@@ -6,6 +6,7 @@ flatbuffers_schemas = [
'dataConsumer.fbs',
'dataProducer.fbs',
'directTransport.fbs',
'liburing.fbs',
'log.fbs',
'message.fbs',
'notification.fbs',
......
include "liburing.fbs";
include "transport.fbs";
namespace FBS.Worker;
......@@ -12,6 +13,7 @@ table DumpResponse {
web_rtc_server_ids: [string] (required);
router_ids: [string] (required);
channel_message_handlers: ChannelMessageHandlers (required);
liburing: FBS.LibUring.Dump;
}
table ResourceUsageResponse {
......
#ifndef MS_DEP_LIBURING_HPP
#define MS_DEP_LIBURING_HPP
#include "DepLibUV.hpp"
#include "FBS/liburing.h"
#include <functional>
#include <liburing.h>
#include <queue>
class DepLibUring
{
public:
using onSendCallback = const std::function<void(bool sent)>;
/* Struct for the user data field of SQE and CQE. */
struct UserData
{
uint8_t store[1500]{};
onSendCallback* cb{ nullptr };
size_t idx{ 0 };
};
/* Number of submission queue entries (SQE). */
static constexpr size_t QueueDepth{ 1024 * 4 };
static bool IsRuntimeSupported();
static void ClassInit();
static void ClassDestroy();
static flatbuffers::Offset<FBS::LibUring::Dump> FillBuffer(flatbuffers::FlatBufferBuilder& builder);
static void StartPollingCQEs();
static void StopPollingCQEs();
static bool PrepareSend(
int sockfd, const void* data, size_t len, const struct sockaddr* addr, onSendCallback* cb);
static bool PrepareWrite(
int sockfd, const void* data1, size_t len1, const void* data2, size_t len2, onSendCallback* cb);
static void Submit();
static void SetActive();
static bool IsActive();
class LibUring;
thread_local static LibUring* liburing;
public:
class LibUring
{
public:
LibUring();
~LibUring();
flatbuffers::Offset<FBS::LibUring::Dump> FillBuffer(flatbuffers::FlatBufferBuilder& builder) const;
void StartPollingCQEs();
void StopPollingCQEs();
bool PrepareSend(
int sockfd, const void* data, size_t len, const struct sockaddr* addr, onSendCallback* cb);
bool PrepareWrite(
int sockfd, const void* data1, size_t len1, const void* data2, size_t len2, onSendCallback* cb);
void Submit();
void SetActive()
{
this->active = true;
}
bool IsActive() const
{
return this->active;
}
io_uring* GetRing()
{
return std::addressof(this->ring);
}
int GetEventFd() const
{
return this->efd;
}
void ReleaseUserDataEntry(size_t idx)
{
this->availableUserDataEntries.push(idx);
}
private:
UserData* GetUserData();
private:
// io_uring instance.
io_uring ring;
// Event file descriptor to watch for completions.
int efd;
// libuv handle used to poll io_uring completions.
uv_poll_t* uvHandle{ nullptr };
// Whether we are currently sending RTP over io_uring.
bool active{ false };
// Pre-allocated UserData entries.
UserData userDataBuffer[QueueDepth]{};
// Indexes of available UserData entries.
std::queue<size_t> availableUserDataEntries;
// Submission queue entry process count.
uint64_t sqeProcessCount{ 0u };
// Submission queue entry miss count.
uint64_t sqeMissCount{ 0u };
// User data miss count.
uint64_t userDataMissCount{ 0u };
};
};
#endif
......@@ -143,6 +143,10 @@ private:
uv_tcp_t* uvHandle{ nullptr };
// Others.
struct sockaddr_storage* localAddr{ nullptr };
#ifdef MS_LIBURING_SUPPORTED
// Local file descriptor for io_uring.
uv_os_fd_t fd{ 0u };
#endif
bool closed{ false };
size_t recvBytes{ 0u };
size_t sentBytes{ 0u };
......
......@@ -103,6 +103,10 @@ private:
// Allocated by this (may be passed by argument).
uv_udp_t* uvHandle{ nullptr };
// Others.
#ifdef MS_LIBURING_SUPPORTED
// Local file descriptor for io_uring.
uv_os_fd_t fd{ 0u };
#endif
bool closed{ false };
size_t recvBytes{ 0u };
size_t sentBytes{ 0u };
......
......@@ -257,6 +257,28 @@ if host_machine.system() == 'windows'
]
endif
if host_machine.system() == 'linux'
kernel_version = run_command('uname', '-r').stdout().strip()
# Enable liburing for kernel versions greather than or equal to 6.
if kernel_version[0].to_int() >= 6
liburing_proj = subproject('liburing', default_options: ['default_library=static'], required: true)
dependencies += [
liburing_proj.get_variable('uring'),
]
link_whole += [
liburing_proj.get_variable('liburing')
]
common_sources += [
'src/DepLibUring.cpp',
]
cpp_args += [
'-DMS_LIBURING_SUPPORTED',
]
endif
endif
libmediasoup_worker = library(
'libmediasoup-worker',
name_prefix: '',
......
#define MS_CLASS "DepLibUring"
// #define MS_LOG_DEV_LEVEL 3
#include "DepLibUring.hpp"
#include "Logger.hpp"
#include "MediaSoupErrors.hpp"
#include <sys/eventfd.h>
#include <sys/utsname.h>
/* Static variables. */
/* liburing instance per thread. */
thread_local DepLibUring::LibUring* DepLibUring::liburing{ nullptr };
/* Completion queue entry array used to retrieve processes tasks. */
thread_local struct io_uring_cqe* cqes[DepLibUring::QueueDepth];
/* Static methods for UV callbacks. */
inline static void onCloseFd(uv_handle_t* handle)
{
delete reinterpret_cast<uv_poll_t*>(handle);
}
inline static void onFdEvent(uv_poll_t* handle, int status, int events)
{
auto* liburing = static_cast<DepLibUring::LibUring*>(handle->data);
auto count = io_uring_peek_batch_cqe(liburing->GetRing(), cqes, DepLibUring::QueueDepth);
// libuv uses level triggering, so we need to read from the socket to reset
// the counter in order to avoid libuv calling this callback indefinitely.
eventfd_t v;
int err = eventfd_read(liburing->GetEventFd(), std::addressof(v));
if (err < 0)
{
MS_ABORT("eventfd_read() failed: %s", std::strerror(-err));
};
for (unsigned int i{ 0 }; i < count; ++i)
{
struct io_uring_cqe* cqe = cqes[i];
auto* userData = static_cast<DepLibUring::UserData*>(io_uring_cqe_get_data(cqe));
if (cqe->res < 0)
{
MS_ERROR("sending failed: %s", std::strerror(-cqe->res));
if (userData->cb)
{
(*userData->cb)(false);
delete userData->cb;
}
}
else
{
if (userData->cb)
{
(*userData->cb)(true);
delete userData->cb;
}
}
io_uring_cqe_seen(liburing->GetRing(), cqe);
liburing->ReleaseUserDataEntry(userData->idx);
}
}
/* Static class methods */
bool DepLibUring::IsRuntimeSupported()
{
// clang-format off
struct utsname buffer{};
// clang-format on
auto err = uname(std::addressof(buffer));
if (err != 0)
{
MS_THROW_ERROR("uname() failed: %s", std::strerror(err));
}
MS_DEBUG_TAG(info, "kernel version: %s", buffer.version);
auto* kernelMayorCstr = buffer.release;
auto kernelMayorLong = strtol(kernelMayorCstr, &kernelMayorCstr, 10);
// liburing `sento` capabilities are supported for kernel versions greather
// than or equal to 6.
return kernelMayorLong >= 6;
}
void DepLibUring::ClassInit()
{
const auto mayor = io_uring_major_version();
const auto minor = io_uring_minor_version();
MS_DEBUG_TAG(info, "liburing version: \"%i.%i\"", mayor, minor);
if (DepLibUring::IsRuntimeSupported())
{
DepLibUring::liburing = new LibUring();
MS_DEBUG_TAG(info, "liburing supported, enabled");
}
else
{
MS_DEBUG_TAG(info, "liburing not supported, not enabled");
}
}
void DepLibUring::ClassDestroy()
{
MS_TRACE();
delete DepLibUring::liburing;
}
flatbuffers::Offset<FBS::LibUring::Dump> DepLibUring::FillBuffer(flatbuffers::FlatBufferBuilder& builder)
{
MS_TRACE();
if (!DepLibUring::liburing)
{
return 0;
}
return DepLibUring::liburing->FillBuffer(builder);
}
void DepLibUring::StartPollingCQEs()
{
MS_TRACE();
if (!DepLibUring::liburing)
{
return;
}
DepLibUring::liburing->StartPollingCQEs();
}
void DepLibUring::StopPollingCQEs()
{
MS_TRACE();
if (!DepLibUring::liburing)
{
return;
}
DepLibUring::liburing->StopPollingCQEs();
}
bool DepLibUring::PrepareSend(
int sockfd, const void* data, size_t len, const struct sockaddr* addr, onSendCallback* cb)
{
MS_TRACE();
MS_ASSERT(DepLibUring::liburing, "DepLibUring::liburing is not set");
return DepLibUring::liburing->PrepareSend(sockfd, data, len, addr, cb);
}
bool DepLibUring::PrepareWrite(
int sockfd, const void* data1, size_t len1, const void* data2, size_t len2, onSendCallback* cb)
{
MS_TRACE();
MS_ASSERT(DepLibUring::liburing, "DepLibUring::liburing is not set");
return DepLibUring::liburing->PrepareWrite(sockfd, data1, len1, data2, len2, cb);
}
void DepLibUring::Submit()
{
MS_TRACE();
if (!DepLibUring::liburing)
{
return;
}
DepLibUring::liburing->Submit();
}
void DepLibUring::SetActive()
{
MS_TRACE();
if (!DepLibUring::liburing)
{
return;
}
DepLibUring::liburing->SetActive();
}
bool DepLibUring::IsActive()
{
MS_TRACE();
if (!DepLibUring::liburing)
{
return false;
}
return DepLibUring::liburing->IsActive();
}
/* Instance methods. */
DepLibUring::LibUring::LibUring()
{
MS_TRACE();
/**
* IORING_SETUP_SINGLE_ISSUER: A hint to the kernel that only a single task
* (or thread) will submit requests, which is used for internal optimisations.
*/
unsigned int flags = IORING_SETUP_SINGLE_ISSUER;
// Initialize io_uring.
auto err = io_uring_queue_init(DepLibUring::QueueDepth, std::addressof(this->ring), flags);
if (err < 0)
{
MS_THROW_ERROR("io_uring_queue_init() failed: %s", std::strerror(-err));
}
// Create an eventfd instance.
this->efd = eventfd(0, 0);
if (this->efd < 0)
{
MS_THROW_ERROR("eventfd() failed: %s", std::strerror(-this->efd));
}
err = io_uring_register_eventfd(std::addressof(this->ring), this->efd);
if (err < 0)
{
MS_THROW_ERROR("io_uring_register_eventfd() failed: %s", std::strerror(-err));
}
// Initialize available UserData entries.
for (size_t i{ 0 }; i < DepLibUring::QueueDepth; ++i)
{
this->availableUserDataEntries.push(i);
}
}
DepLibUring::LibUring::~LibUring()
{
MS_TRACE();
// Close the event file descriptor.
const auto err = close(this->efd);
if (err != 0)
{
MS_ABORT("close() failed: %s", std::strerror(-err));
}
// Close the ring.
io_uring_queue_exit(std::addressof(this->ring));
}
flatbuffers::Offset<FBS::LibUring::Dump> DepLibUring::LibUring::FillBuffer(
flatbuffers::FlatBufferBuilder& builder) const
{
MS_TRACE();
return FBS::LibUring::CreateDump(
builder, this->sqeProcessCount, this->sqeMissCount, this->userDataMissCount);
}
void DepLibUring::LibUring::StartPollingCQEs()
{
MS_TRACE();
// Watch the event file descriptor for completions.
this->uvHandle = new uv_poll_t;
auto err = uv_poll_init(DepLibUV::GetLoop(), this->uvHandle, this->efd);
if (err != 0)
{
delete this->uvHandle;
MS_THROW_ERROR("uv_poll_init() failed: %s", uv_strerror(err));
}
this->uvHandle->data = this;
err = uv_poll_start(this->uvHandle, UV_READABLE, static_cast<uv_poll_cb>(onFdEvent));
if (err != 0)
{
MS_THROW_ERROR("uv_poll_start() failed: %s", uv_strerror(err));
}
}
void DepLibUring::LibUring::StopPollingCQEs()
{
MS_TRACE();
this->uvHandle->data = nullptr;
// Stop polling the event file descriptor.
auto err = uv_poll_stop(this->uvHandle);
if (err != 0)
{
MS_ABORT("uv_poll_stop() failed: %s", uv_strerror(err));
}
// NOTE: Handles that wrap file descriptors are clossed immediately.
uv_close(reinterpret_cast<uv_handle_t*>(this->uvHandle), static_cast<uv_close_cb>(onCloseFd));
}
bool DepLibUring::LibUring::PrepareSend(
int sockfd, const void* data, size_t len, const struct sockaddr* addr, onSendCallback* cb)
{
MS_TRACE();
auto* userData = this->GetUserData();
if (!userData)
{
MS_WARN_DEV("no user data entry available");
this->userDataMissCount++;
return false;
}
auto* sqe = io_uring_get_sqe(std::addressof(this->ring));
if (!sqe)
{
MS_WARN_DEV("no sqe available");
this->sqeMissCount++;
return false;
}
std::memcpy(userData->store, data, len);
userData->cb = cb;
io_uring_sqe_set_data(sqe, userData);
socklen_t addrlen = 0;
if (addr->sa_family == AF_INET)
{
addrlen = sizeof(struct sockaddr_in);
}
else if (addr->sa_family == AF_INET6)
{
addrlen = sizeof(struct sockaddr_in6);
}
io_uring_prep_sendto(sqe, sockfd, userData->store, len, 0, addr, addrlen);
this->sqeProcessCount++;
return true;
}
bool DepLibUring::LibUring::PrepareWrite(
int sockfd, const void* data1, size_t len1, const void* data2, size_t len2, onSendCallback* cb)
{
MS_TRACE();
auto* userData = this->GetUserData();
if (!userData)
{
MS_WARN_DEV("no user data entry available");
this->userDataMissCount++;
return false;
}
auto* sqe = io_uring_get_sqe(std::addressof(this->ring));
if (!sqe)
{
MS_WARN_DEV("no sqe available");
this->sqeMissCount++;
return false;
}
std::memcpy(userData->store, data1, len1);
std::memcpy(userData->store + len1, data2, len2);
userData->cb = cb;
io_uring_sqe_set_data(sqe, userData);
io_uring_prep_write(sqe, sockfd, userData->store, len1 + len2, 0);
this->sqeProcessCount++;
return true;
}
void DepLibUring::LibUring::Submit()
{
MS_TRACE();
// Unset active flag.
this->active = false;
auto err = io_uring_submit(std::addressof(this->ring));
if (err >= 0)
{
MS_DEBUG_DEV("%i submission queue entries submitted", err);
}
else
{
MS_ERROR("io_uring_submit() failed: %s", std::strerror(-err));
}
}
DepLibUring::UserData* DepLibUring::LibUring::GetUserData()
{
MS_TRACE();
if (this->availableUserDataEntries.empty())
{
MS_WARN_DEV("no user data entry available");
return nullptr;
}
auto idx = this->availableUserDataEntries.front();
this->availableUserDataEntries.pop();
auto* userData = std::addressof(this->userDataBuffer[idx]);
userData->idx = idx;
return userData;
}
......@@ -2,6 +2,9 @@
// #define MS_LOG_DEV_LEVEL 3
#include "RTC/Router.hpp"
#ifdef MS_LIBURING_SUPPORTED
#include "DepLibUring.hpp"
#endif
#include "Logger.hpp"
#include "MediaSoupErrors.hpp"
#include "Utils.hpp"
......@@ -660,6 +663,11 @@ namespace RTC
// Clone only happens if needed.
std::shared_ptr<RTC::RtpPacket> sharedPacket;
#ifdef MS_LIBURING_SUPPORTED
// Activate liburing usage.
DepLibUring::SetActive();
#endif
for (auto* consumer : consumers)
{
// Update MID RTP extension value.
......@@ -672,6 +680,11 @@ namespace RTC
consumer->SendRtpPacket(packet, sharedPacket);
}
#ifdef MS_LIBURING_SUPPORTED
// Submit all prepared submission entries.
DepLibUring::Submit();
#endif
}
auto it = this->mapProducerRtpObservers.find(producer);
......
......@@ -2,6 +2,9 @@
// #define MS_LOG_DEV_LEVEL 3
#include "RTC/RtpStreamSend.hpp"
#ifdef MS_LIBURING_SUPPORTED
#include "DepLibUring.hpp"
#endif
#include "Logger.hpp"
#include "Utils.hpp"
#include "RTC/RtpDictionaries.hpp"
......@@ -125,6 +128,11 @@ namespace RTC
this->nackCount++;
#ifdef MS_LIBURING_SUPPORTED
// Activate liburing usage.
DepLibUring::SetActive();
#endif
for (auto it = nackPacket->Begin(); it != nackPacket->End(); ++it)
{
RTC::RTCP::FeedbackRtpNackItem* item = *it;
......@@ -164,6 +172,11 @@ namespace RTC
}
}
}
#ifdef MS_LIBURING_SUPPORTED
// Submit all prepared submission entries.
DepLibUring::Submit();
#endif
}
void RtpStreamSend::ReceiveKeyFrameRequest(RTC::RTCP::FeedbackPs::MessageType messageType)
......
......@@ -2,6 +2,10 @@
#define MS_CLASS "RTC::Transport"
// #define MS_LOG_DEV_LEVEL 3
#include "RTC/Transport.hpp"
#ifdef MS_LIBURING_SUPPORTED
#include "DepLibUring.hpp"
#endif
#include "Logger.hpp"
#include "MediaSoupErrors.hpp"
#include "Utils.hpp"
......@@ -19,7 +23,6 @@
#include "RTC/SimpleConsumer.hpp"
#include "RTC/SimulcastConsumer.hpp"
#include "RTC/SvcConsumer.hpp"
#include "RTC/Transport.hpp"
#include <libwebrtc/modules/rtp_rtcp/include/rtp_rtcp_defines.h> // webrtc::RtpPacketSendInfo
#include <iterator> // std::ostream_iterator
#include <map> // std::multimap
......@@ -2151,6 +2154,11 @@ namespace RTC
std::unique_ptr<RTC::RTCP::CompoundPacket> packet{ new RTC::RTCP::CompoundPacket() };
#ifdef MS_LIBURING_SUPPORTED
// Activate liburing usage.
DepLibUring::SetActive();
#endif
for (auto& kv : this->mapConsumers)
{
auto* consumer = kv.second;
......@@ -2194,6 +2202,11 @@ namespace RTC
{
SendRtcpCompoundPacket(packet.get());
}
#ifdef MS_LIBURING_SUPPORTED
// Submit all prepared submission entries.
DepLibUring::Submit();
#endif
}
void Transport::DistributeAvailableOutgoingBitrate()
......
......@@ -3,6 +3,9 @@
#include "Worker.hpp"
#include "ChannelMessageRegistrator.hpp"
#ifdef MS_LIBURING_SUPPORTED
#include "DepLibUring.hpp"
#endif
#include "DepLibUV.hpp"
#include "DepUsrSCTP.hpp"
#include "Logger.hpp"
......@@ -40,6 +43,11 @@ Worker::Worker(::Channel::ChannelSocket* channel) : channel(channel)
// Create the Checker instance in DepUsrSCTP.
DepUsrSCTP::CreateChecker();
#ifdef MS_LIBURING_SUPPORTED
// Start polling CQEs, which will create a uv_pool_t handle.
DepLibUring::StartPollingCQEs();
#endif
// Tell the Node process that we are running.
this->shared->channelNotifier->Emit(
std::to_string(Logger::pid), FBS::Notification::Event::WORKER_RUNNING);
......@@ -97,6 +105,11 @@ void Worker::Close()
// Close the Checker instance in DepUsrSCTP.
DepUsrSCTP::CloseChecker();
#ifdef MS_LIBURING_SUPPORTED
// Stop polling CQEs, which will close the uv_pool_t handle.
DepLibUring::StopPollingCQEs();
#endif
// Close the Channel.
this->channel->Close();
}
......@@ -129,7 +142,16 @@ flatbuffers::Offset<FBS::Worker::DumpResponse> Worker::FillBuffer(
auto channelMessageHandlers = this->shared->channelMessageRegistrator->FillBuffer(builder);
return FBS::Worker::CreateDumpResponseDirect(
builder, Logger::pid, &webRtcServerIds, &routerIds, channelMessageHandlers);
builder,
Logger::pid,
&webRtcServerIds,
&routerIds,
channelMessageHandlers
#ifdef MS_LIBURING_SUPPORTED
,
DepLibUring::FillBuffer(builder)
#endif
);
}
flatbuffers::Offset<FBS::Worker::ResourceUsageResponse> Worker::FillBufferResourceUsage(
......
......@@ -3,6 +3,9 @@
#include "handles/TcpConnectionHandle.hpp"
#include "DepLibUV.hpp"
#ifdef MS_LIBURING_SUPPORTED
#include "DepLibUring.hpp"
#endif
#include "Logger.hpp"
#include "MediaSoupErrors.hpp"
#include "Utils.hpp"
......@@ -199,6 +202,15 @@ void TcpConnectionHandle::Start()
{
MS_THROW_ERROR("error setting peer IP and port");
}
#ifdef MS_LIBURING_SUPPORTED
err = uv_fileno(reinterpret_cast<uv_handle_t*>(this->uvHandle), std::addressof(this->fd));
if (err != 0)
{
MS_THROW_ERROR("uv_fileno() failed: %s", uv_strerror(err));
}
#endif
}
void TcpConnectionHandle::Write(
......@@ -232,6 +244,30 @@ void TcpConnectionHandle::Write(
return;
}
#ifdef MS_LIBURING_SUPPORTED
{
if (!DepLibUring::IsActive())
{
goto write_libuv;
}
// Prepare the data to be sent.
// NOTE: If all SQEs are currently in use or no UserData entry is available we'll
// fall back to libuv.
auto prepared = DepLibUring::PrepareWrite(this->fd, data1, len1, data2, len2, cb);
if (!prepared)
{
MS_DEBUG_DEV("cannot write via liburing, fallback to libuv");
goto write_libuv;
}
return;
}
#endif
write_libuv:
const size_t totalLen = len1 + len2;
uv_buf_t buffers[2];
int written{ 0 };
......
......@@ -2,6 +2,9 @@
// #define MS_LOG_DEV_LEVEL 3
#include "handles/UdpSocketHandle.hpp"
#ifdef MS_LIBURING_SUPPORTED
#include "DepLibUring.hpp"
#endif
#include "Logger.hpp"
#include "MediaSoupErrors.hpp"
#include "Utils.hpp"
......@@ -84,6 +87,15 @@ UdpSocketHandle::UdpSocketHandle(uv_udp_t* uvHandle) : uvHandle(uvHandle)
MS_THROW_ERROR("error setting local IP and port");
}
#ifdef MS_LIBURING_SUPPORTED
err = uv_fileno(reinterpret_cast<uv_handle_t*>(this->uvHandle), std::addressof(this->fd));
if (err != 0)
{
MS_THROW_ERROR("uv_fileno() failed: %s", uv_strerror(err));
}
#endif
}
UdpSocketHandle::~UdpSocketHandle()
......@@ -157,6 +169,30 @@ void UdpSocketHandle::Send(
return;
}
#ifdef MS_LIBURING_SUPPORTED
{
if (!DepLibUring::IsActive())
{
goto send_libuv;
}
// Prepare the data to be sent.
// NOTE: If all SQEs are currently in use or no UserData entry is available we'll
// fall back to libuv.
auto prepared = DepLibUring::PrepareSend(this->fd, data, len, addr, cb);
if (!prepared)
{
MS_DEBUG_DEV("cannot send via liburing, fallback to libuv");
goto send_libuv;
}
return;
}
#endif
send_libuv:
// First try uv_udp_try_send(). In case it can not directly send the datagram
// then build a uv_req_t and use uv_udp_send().
......
......@@ -3,6 +3,9 @@
#include "common.hpp"
#include "DepLibSRTP.hpp"
#ifdef MS_LIBURING_SUPPORTED
#include "DepLibUring.hpp"
#endif
#include "DepLibUV.hpp"
#include "DepLibWebRTC.hpp"
#include "DepOpenSSL.hpp"
......@@ -124,6 +127,9 @@ extern "C" int mediasoup_worker_run(
DepOpenSSL::ClassInit();
DepLibSRTP::ClassInit();
DepUsrSCTP::ClassInit();
#ifdef MS_LIBURING_SUPPORTED
DepLibUring::ClassInit();
#endif
DepLibWebRTC::ClassInit();
Utils::Crypto::ClassInit();
RTC::DtlsTransport::ClassInit();
......@@ -141,6 +147,9 @@ extern "C" int mediasoup_worker_run(
DepLibSRTP::ClassDestroy();
Utils::Crypto::ClassDestroy();
DepLibWebRTC::ClassDestroy();
#ifdef MS_LIBURING_SUPPORTED
DepLibUring::ClassDestroy();
#endif
RTC::DtlsTransport::ClassDestroy();
DepUsrSCTP::ClassDestroy();
DepLibUV::ClassDestroy();
......
[wrap-file]
directory = liburing-liburing-2.4
source_url = https://github.com/axboe/liburing/archive/refs/tags/liburing-2.4.tar.gz
source_filename = liburing-2.4.tar.gz
source_hash = 2398ec82d967a6f903f3ae1fd4541c754472d3a85a584dc78c5da2fabc90706b
patch_filename = liburing_2.4-1_patch.zip
patch_url = https://wrapdb.mesonbuild.com/v2/liburing_2.4-1/get_patch
patch_hash = 0dd939828da6a7c6d22c0f4db879405e74f9ac7153927c365642a28f871c92c2
source_fallback_url = https://github.com/mesonbuild/wrapdb/releases/download/liburing_2.4-1/liburing-2.4.tar.gz
wrapdb_version = 2.4-1
[provide]
dependency_names = liburing
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论