Unverified 提交 f676ee33 authored 作者: Nazar Mokrynskyi's avatar Nazar Mokrynskyi 提交者: GitHub

Merge pull request #703 from nazar-pc/fix-drop-ordering

Fix drop ordering
......@@ -398,14 +398,11 @@ impl Inner {
let request = RouterCloseRequest {
internal: RouterInternal { router_id: self.id },
};
let worker = self.worker.clone();
self.executor
.spawn(async move {
if let Err(error) = channel.request(request).await {
error!("router closing failed on drop: {}", error);
}
drop(worker);
})
.detach();
}
......
......@@ -110,14 +110,11 @@ impl Inner {
rtp_observer_id: self.id,
},
};
let router = self.router.clone();
self.executor
.spawn(async move {
if let Err(error) = channel.request(request).await {
error!("active speaker observer closing failed on drop: {}", error);
}
drop(router);
})
.detach();
}
......
......@@ -124,14 +124,11 @@ impl Inner {
rtp_observer_id: self.id,
},
};
let router = self.router.clone();
self.executor
.spawn(async move {
if let Err(error) = channel.request(request).await {
error!("audio level observer closing failed on drop: {}", error);
}
drop(router);
})
.detach();
}
......
......@@ -409,19 +409,15 @@ impl Inner {
producer_id: self.producer_id,
},
};
let producer = self.weak_producer.upgrade();
let transport = self.transport.clone();
let weak_producer = self.weak_producer.clone();
self.executor
.spawn(async move {
if producer.is_some() {
if weak_producer.upgrade().is_some() {
if let Err(error) = channel.request(request).await {
error!("consumer closing failed on drop: {}", error);
}
}
drop(producer);
drop(transport);
})
.detach();
}
......
......@@ -238,19 +238,15 @@ impl Inner {
data_producer_id: self.data_producer_id,
},
};
let data_producer = self.weak_data_producer.upgrade();
let transport = self.transport.clone();
let weak_data_producer = self.weak_data_producer.clone();
self.executor
.spawn(async move {
if data_producer.is_some() {
if weak_data_producer.upgrade().is_some() {
if let Err(error) = channel.request(request).await {
error!("consumer closing failed on drop: {}", error);
}
}
drop(data_producer);
drop(transport);
})
.detach();
}
......
......@@ -168,14 +168,11 @@ impl Inner {
data_producer_id: self.id,
},
};
let transport = self.transport.clone();
self.executor
.spawn(async move {
if let Err(error) = channel.request(request).await {
error!("data producer closing failed on drop: {}", error);
}
drop(transport);
})
.detach();
}
......
......@@ -176,14 +176,11 @@ impl Inner {
transport_id: self.id,
},
};
let router = self.router.clone();
self.executor
.spawn(async move {
if let Err(error) = channel.request(request).await {
error!("transport closing failed on drop: {}", error);
}
drop(router);
})
.detach();
}
......
......@@ -225,14 +225,11 @@ impl Inner {
transport_id: self.id,
},
};
let router = self.router.clone();
self.executor
.spawn(async move {
if let Err(error) = channel.request(request).await {
error!("transport closing failed on drop: {}", error);
}
drop(router);
})
.detach();
}
......
......@@ -257,14 +257,11 @@ impl Inner {
transport_id: self.id,
},
};
let router = self.router.clone();
self.executor
.spawn(async move {
if let Err(error) = channel.request(request).await {
error!("transport closing failed on drop: {}", error);
}
drop(router);
})
.detach();
}
......
......@@ -334,14 +334,11 @@ impl Inner {
producer_id: self.id,
},
};
let transport = self.transport.clone();
self.executor
.spawn(async move {
if let Err(error) = channel.request(request).await {
error!("producer closing failed on drop: {}", error);
}
drop(transport);
})
.detach();
}
......
......@@ -309,14 +309,11 @@ impl Inner {
transport_id: self.id,
},
};
let router = self.router.clone();
self.executor
.spawn(async move {
if let Err(error) = channel.request(request).await {
error!("transport closing failed on drop: {}", error);
}
drop(router);
})
.detach();
}
......
......@@ -268,7 +268,7 @@ impl Drop for Inner {
}
impl Inner {
async fn new(
async fn new<OE: FnOnce() + Send + 'static>(
executor: Arc<Executor<'static>>,
WorkerSettings {
app_data,
......@@ -278,6 +278,7 @@ impl Inner {
dtls_files,
}: WorkerSettings,
worker_manager: WorkerManager,
on_exit: OE,
) -> io::Result<Arc<Self>> {
debug!("new()");
......@@ -321,12 +322,15 @@ impl Inner {
spawn_args.join(" ")
);
let (mut status_sender, status_receiver) = async_oneshot::oneshot();
let WorkerRunResult {
channel,
payload_channel,
status_receiver,
buffer_worker_messages_guard,
} = utils::run_worker_with_channels(id, Arc::clone(&executor), spawn_args);
} = utils::run_worker_with_channels(id, Arc::clone(&executor), spawn_args, move |result| {
let _ = status_sender.send(result);
on_exit();
});
let handlers = Handlers::default();
......@@ -512,12 +516,13 @@ impl fmt::Debug for Worker {
}
impl Worker {
pub(super) async fn new(
pub(super) async fn new<OE: FnOnce() + Send + 'static>(
executor: Arc<Executor<'static>>,
worker_settings: WorkerSettings,
worker_manager: WorkerManager,
on_exit: OE,
) -> io::Result<Self> {
let inner = Inner::new(executor, worker_settings, worker_manager).await?;
let inner = Inner::new(executor, worker_settings, worker_manager, on_exit).await?;
Ok(Self { inner })
}
......
......@@ -3,7 +3,6 @@ use crate::worker::channel::BufferMessagesGuard;
use crate::worker::{Channel, PayloadChannel, WorkerId};
use async_executor::Executor;
use async_fs::File;
use async_oneshot::Receiver;
use std::ffi::CString;
use std::mem;
use std::os::raw::{c_char, c_int};
......@@ -46,20 +45,22 @@ fn pipe() -> [c_int; 2] {
pub(super) struct WorkerRunResult {
pub(super) channel: Channel,
pub(super) payload_channel: PayloadChannel,
pub(super) status_receiver: Receiver<Result<(), ExitError>>,
pub(super) buffer_worker_messages_guard: BufferMessagesGuard,
}
pub(super) fn run_worker_with_channels(
pub(super) fn run_worker_with_channels<OE>(
id: WorkerId,
executor: Arc<Executor<'static>>,
args: Vec<String>,
) -> WorkerRunResult {
on_exit: OE,
) -> WorkerRunResult
where
OE: FnOnce(Result<(), ExitError>) + Send + 'static,
{
let [producer_fd_read, producer_fd_write] = pipe();
let [consumer_fd_read, consumer_fd_write] = pipe();
let [producer_payload_fd_read, producer_payload_fd_write] = pipe();
let [consumer_payload_fd_read, consumer_payload_fd_write] = pipe();
let (mut status_sender, status_receiver) = async_oneshot::oneshot();
let producer_file = unsafe { File::from_raw_fd(producer_fd_write) };
let consumer_file = unsafe { File::from_raw_fd(consumer_fd_read) };
......@@ -96,7 +97,7 @@ pub(super) fn run_worker_with_channels(
)
};
let _ = status_sender.send(match status_code {
on_exit(match status_code {
0 => Ok(()),
1 => Err(ExitError::Generic),
42 => Err(ExitError::Settings),
......@@ -108,7 +109,6 @@ pub(super) fn run_worker_with_channels(
WorkerRunResult {
channel,
payload_channel,
status_receiver,
buffer_worker_messages_guard,
}
}
......@@ -3,14 +3,18 @@
#[cfg(test)]
mod tests;
use crate::worker::{Worker, WorkerSettings};
use crate::worker::{Worker, WorkerId, WorkerSettings};
use async_executor::Executor;
use async_oneshot::Sender;
use event_listener_primitives::{Bag, HandlerId};
use futures_lite::future;
use log::debug;
use parking_lot::Mutex;
use std::collections::HashMap;
use std::ops::DerefMut;
use std::sync::mpsc;
use std::sync::Arc;
use std::{fmt, io};
use std::{fmt, io, mem};
#[derive(Default)]
struct Handlers {
......@@ -20,10 +24,22 @@ struct Handlers {
struct Inner {
executor: Arc<Executor<'static>>,
handlers: Handlers,
/// Mapping from worker ID to the close event receiver
workers: Arc<Mutex<HashMap<WorkerId, mpsc::Receiver<()>>>>,
/// This field is only used in order to be dropped with the worker manager itself to stop the
/// thread created with `WorkerManager::new()` call
_stop_sender: Option<Sender<()>>,
}
impl Drop for Inner {
fn drop(&mut self) {
let workers = mem::take(self.workers.lock().deref_mut());
for exit_receiver in workers.into_values() {
let _ = exit_receiver.recv();
}
}
}
/// Container that creates [`Worker`] instances.
///
/// # Examples
......@@ -83,6 +99,7 @@ impl WorkerManager {
let inner = Arc::new(Inner {
executor,
handlers,
workers: Arc::default(),
_stop_sender: Some(stop_sender),
});
......@@ -96,6 +113,7 @@ impl WorkerManager {
let inner = Arc::new(Inner {
executor,
handlers,
workers: Arc::default(),
_stop_sender: None,
});
......@@ -108,16 +126,33 @@ impl WorkerManager {
pub async fn create_worker(&self, worker_settings: WorkerSettings) -> io::Result<Worker> {
debug!("create_worker()");
let (exit_sender, exit_receiver) = mpsc::channel();
let id = Arc::new(Mutex::new(None));
let worker = Worker::new(
Arc::clone(&self.inner.executor),
worker_settings,
self.clone(),
{
let id = Arc::clone(&id);
let workers = Arc::clone(&self.inner.workers);
move || {
let _ = exit_sender.send(());
let id = id.lock().take().unwrap();
workers.lock().remove(&id);
}
},
)
.await?;
self.inner.handlers.new_worker.call(|callback| {
callback(&worker);
});
id.lock().replace(worker.id());
self.inner.workers.lock().insert(worker.id(), exit_receiver);
Ok(worker)
}
......
......@@ -10,8 +10,8 @@
/* Static. */
static constexpr size_t CheckerInterval{ 10u }; // In ms.
static std::mutex globalSyncMutex;
static size_t globalInstances = 0;
static std::mutex GlobalSyncMutex;
static size_t GlobalInstances{ 0u };
/* Static methods for usrsctp global callbacks. */
......@@ -65,42 +65,38 @@ void DepUsrSCTP::ClassInit()
MS_DEBUG_TAG(info, "usrsctp");
{
std::lock_guard<std::mutex> lock(globalSyncMutex);
std::lock_guard<std::mutex> lock(GlobalSyncMutex);
if (globalInstances == 0)
{
usrsctp_init_nothreads(0, onSendSctpData, sctpDebug);
if (GlobalInstances == 0)
{
usrsctp_init_nothreads(0, onSendSctpData, sctpDebug);
// Disable explicit congestion notifications (ecn).
usrsctp_sysctl_set_sctp_ecn_enable(0);
// Disable explicit congestion notifications (ecn).
usrsctp_sysctl_set_sctp_ecn_enable(0);
#ifdef SCTP_DEBUG
usrsctp_sysctl_set_sctp_debug_on(SCTP_DEBUG_ALL);
usrsctp_sysctl_set_sctp_debug_on(SCTP_DEBUG_ALL);
#endif
}
++globalInstances;
}
++GlobalInstances;
}
void DepUsrSCTP::ClassDestroy()
{
MS_TRACE();
{
std::lock_guard<std::mutex> lock(globalSyncMutex);
--globalInstances;
std::lock_guard<std::mutex> lock(GlobalSyncMutex);
--GlobalInstances;
if (globalInstances == 0)
{
usrsctp_finish();
if (GlobalInstances == 0)
{
usrsctp_finish();
numSctpAssociations = 0u;
nextSctpAssociationId = 0u;
numSctpAssociations = 0u;
nextSctpAssociationId = 0u;
DepUsrSCTP::mapIdSctpAssociation.clear();
}
DepUsrSCTP::mapIdSctpAssociation.clear();
}
}
......@@ -126,7 +122,7 @@ uintptr_t DepUsrSCTP::GetNextSctpAssociationId()
{
MS_TRACE();
std::lock_guard<std::mutex> lock(globalSyncMutex);
std::lock_guard<std::mutex> lock(GlobalSyncMutex);
// NOTE: usrsctp_connect() fails with a value of 0.
if (DepUsrSCTP::nextSctpAssociationId == 0u)
......@@ -150,7 +146,7 @@ void DepUsrSCTP::RegisterSctpAssociation(RTC::SctpAssociation* sctpAssociation)
{
MS_TRACE();
std::lock_guard<std::mutex> lock(globalSyncMutex);
std::lock_guard<std::mutex> lock(GlobalSyncMutex);
MS_ASSERT(DepUsrSCTP::checker != nullptr, "Checker not created");
......@@ -170,7 +166,7 @@ void DepUsrSCTP::DeregisterSctpAssociation(RTC::SctpAssociation* sctpAssociation
{
MS_TRACE();
std::lock_guard<std::mutex> lock(globalSyncMutex);
std::lock_guard<std::mutex> lock(GlobalSyncMutex);
MS_ASSERT(DepUsrSCTP::checker != nullptr, "Checker not created");
......@@ -187,7 +183,7 @@ RTC::SctpAssociation* DepUsrSCTP::RetrieveSctpAssociation(uintptr_t id)
{
MS_TRACE();
std::lock_guard<std::mutex> lock(globalSyncMutex);
std::lock_guard<std::mutex> lock(GlobalSyncMutex);
auto it = DepUsrSCTP::mapIdSctpAssociation.find(id);
......
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论