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