use crate::execution_engine::DefaultExecutionEngine;
use crate::execution_engine::ExecutionEngine;
use crate::execution_engine::QueryStageExecutor;
use crate::execution_loop::any_to_string;
use crate::metrics::ExecutorMetricsCollector;
use crate::metrics::LoggingMetricsCollector;
use crate::runtime_cache::SessionRuntimeCache;
use ballista_core::ConfigProducer;
use ballista_core::JobId;
use ballista_core::RuntimeProducer;
use ballista_core::error::BallistaError;
use ballista_core::registry::BallistaFunctionRegistry;
use ballista_core::serde::protobuf::{ExecutorRegistration, ShuffleWritePartition};
use ballista_core::serde::scheduler::TaskKey;
use dashmap::DashMap;
use datafusion::execution::context::TaskContext;
use datafusion::execution::runtime_env::RuntimeEnv;
use datafusion::prelude::SessionConfig;
use futures::FutureExt;
use futures::future::AbortHandle;
use futures::task::AtomicWaker;
use log::error;
use log::warn;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
pub struct TasksDrainedFuture(
pub Arc<Executor>,
);
impl Future for TasksDrainedFuture {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
self.0.tasks_drained_waker.register(cx.waker());
if !self.0.abort_handles.is_empty() {
Poll::Pending
} else {
Poll::Ready(())
}
}
}
type AbortHandles = Arc<DashMap<TaskKey, AbortHandle>>;
#[derive(Clone)]
pub struct Executor {
pub metadata: ExecutorRegistration,
pub work_dir: String,
pub function_registry: Arc<BallistaFunctionRegistry>,
pub runtime_producer: RuntimeProducer,
pub config_producer: ConfigProducer,
pub metrics_collector: Arc<dyn ExecutorMetricsCollector>,
pub vcores: usize,
abort_handles: AbortHandles,
tasks_drained_waker: Arc<AtomicWaker>,
pub(crate) execution_engine: Arc<dyn ExecutionEngine>,
session_runtime_cache: Option<Arc<dyn SessionRuntimeCache>>,
}
impl Executor {
pub fn new_basic(
metadata: ExecutorRegistration,
work_dir: &str,
runtime_producer: RuntimeProducer,
config_producer: ConfigProducer,
vcores: usize,
) -> Self {
Self::new(
metadata,
work_dir,
runtime_producer,
config_producer,
Arc::new(BallistaFunctionRegistry::default()),
Arc::new(LoggingMetricsCollector::default()),
vcores,
Arc::new(DefaultExecutionEngine::new()),
)
}
#[allow(clippy::too_many_arguments)]
pub fn new(
metadata: ExecutorRegistration,
work_dir: &str,
runtime_producer: RuntimeProducer,
config_producer: ConfigProducer,
function_registry: Arc<BallistaFunctionRegistry>,
metrics_collector: Arc<dyn ExecutorMetricsCollector>,
vcores: usize,
execution_engine: Arc<dyn ExecutionEngine>,
) -> Self {
Self {
metadata,
work_dir: work_dir.to_owned(),
function_registry,
runtime_producer,
config_producer,
metrics_collector,
vcores,
abort_handles: Default::default(),
tasks_drained_waker: Default::default(),
execution_engine,
session_runtime_cache: None,
}
}
pub fn with_default_execution_engine(
metadata: ExecutorRegistration,
work_dir: &str,
runtime_producer: RuntimeProducer,
config_producer: ConfigProducer,
function_registry: Arc<BallistaFunctionRegistry>,
metrics_collector: Arc<dyn ExecutorMetricsCollector>,
vcores: usize,
) -> Self {
Self {
metadata,
work_dir: work_dir.to_owned(),
function_registry,
runtime_producer,
config_producer,
metrics_collector,
vcores,
abort_handles: Default::default(),
tasks_drained_waker: Default::default(),
execution_engine: Arc::new(DefaultExecutionEngine::new()),
session_runtime_cache: None,
}
}
}
impl Executor {
fn wake_tasks_drained(&self) {
if self.abort_handles.is_empty() {
self.tasks_drained_waker.wake();
}
}
pub fn produce_runtime(
&self,
config: &SessionConfig,
) -> datafusion::error::Result<Arc<RuntimeEnv>> {
(self.runtime_producer)(config)
}
pub fn with_session_runtime_cache(
mut self,
cache: Option<Arc<dyn SessionRuntimeCache>>,
) -> Self {
self.session_runtime_cache = cache;
self
}
pub fn produce_runtime_for_session(
&self,
session_id: &str,
config: &SessionConfig,
vcores_consumed: u32,
) -> datafusion::error::Result<Arc<RuntimeEnv>> {
match &self.session_runtime_cache {
Some(cache) => cache.produce_runtime(session_id, config, vcores_consumed),
None => (self.runtime_producer)(config),
}
}
pub fn produce_config(&self) -> SessionConfig {
(self.config_producer)()
}
pub async fn execute_query_stage(
&self,
key: TaskKey,
query_stage_exec: Arc<dyn QueryStageExecutor>,
task_ctx: Arc<TaskContext>,
) -> Result<Vec<ShuffleWritePartition>, BallistaError> {
let (task, abort_handle) = futures::future::abortable(
query_stage_exec.execute_query_stage(key.task_id, task_ctx),
);
self.abort_handles.insert(key.clone(), abort_handle);
let partitions = match std::panic::AssertUnwindSafe(task).catch_unwind().await {
Ok(Ok(result)) => result.map_err(BallistaError::from),
Ok(Err(_)) => {
warn!("Task has been aborted!");
Err(BallistaError::Cancelled)
}
Err(p) => {
let error_msg = format!("{:#?}", any_to_string(&p));
error!("{error_msg}");
Err(BallistaError::Internal(error_msg))
}
};
self.abort_handles.remove(&key);
self.wake_tasks_drained();
self.metrics_collector.record_stage(
&key.job_id,
key.stage_id,
key.task_id,
query_stage_exec,
);
partitions
}
pub async fn cancel_task(
&self,
job_id: JobId,
stage_id: usize,
task_id: usize,
) -> Result<bool, BallistaError> {
if let Some(handle) = self.abort_handles.get(&TaskKey {
job_id,
stage_id,
task_id,
}) {
handle.abort();
Ok(true)
} else {
Ok(false)
}
}
pub fn work_dir(&self) -> &str {
&self.work_dir
}
pub fn active_task_count(&self) -> usize {
self.abort_handles.len()
}
}
#[cfg(test)]
mod test {
use crate::execution_engine::{DefaultQueryStageExec, ShuffleWriterVariant};
use crate::executor::{Executor, TasksDrainedFuture};
use crate::runtime_cache::{
DefaultSessionRuntimeCache, MemoryPoolPolicy, SessionRuntimeCache,
};
use ballista_core::RuntimeProducer;
use ballista_core::error::BallistaError;
use ballista_core::execution_plans::ShuffleWriterExec;
use ballista_core::serde::protobuf::{ExecutorRegistration, ShuffleWritePartition};
use ballista_core::serde::scheduler::TaskKey;
use ballista_core::utils::default_config_producer;
use datafusion::arrow::datatypes::{Schema, SchemaRef};
use datafusion::arrow::record_batch::RecordBatch;
use datafusion::common::tree_node::TreeNodeRecursion;
use datafusion::error::{DataFusionError, Result};
use datafusion::execution::context::TaskContext;
use datafusion::execution::runtime_env::RuntimeEnv;
use datafusion::physical_expr::PhysicalExpr;
use datafusion::physical_plan::{
DisplayAs, DisplayFormatType, ExecutionPlan, Partitioning, PlanProperties,
RecordBatchStream, SendableRecordBatchStream,
};
use datafusion::prelude::SessionConfig;
use datafusion::prelude::SessionContext;
use futures::Stream;
use futures::task::{ArcWake, waker_ref};
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::task::{Context, Poll};
use std::time::Duration;
use tempfile::TempDir;
struct NeverendingRecordBatchStream;
#[derive(Default)]
struct WakeCounter(AtomicUsize);
impl ArcWake for WakeCounter {
fn wake_by_ref(arc_self: &Arc<Self>) {
arc_self.0.fetch_add(1, Ordering::SeqCst);
}
}
impl RecordBatchStream for NeverendingRecordBatchStream {
fn schema(&self) -> SchemaRef {
Arc::new(Schema::empty())
}
}
impl Stream for NeverendingRecordBatchStream {
type Item = Result<RecordBatch, DataFusionError>;
fn poll_next(
self: Pin<&mut Self>,
_cx: &mut Context<'_>,
) -> Poll<Option<Self::Item>> {
Poll::Pending
}
}
#[derive(Debug)]
pub struct NeverendingOperator {
properties: Arc<PlanProperties>,
}
impl NeverendingOperator {
fn new() -> Self {
NeverendingOperator {
properties: Arc::new(PlanProperties::new(
datafusion::physical_expr::EquivalenceProperties::new(Arc::new(
Schema::empty(),
)),
Partitioning::UnknownPartitioning(1),
datafusion::physical_plan::execution_plan::EmissionType::Incremental,
datafusion::physical_plan::execution_plan::Boundedness::Bounded,
)),
}
}
}
impl DisplayAs for NeverendingOperator {
fn fmt_as(
&self,
t: DisplayFormatType,
f: &mut std::fmt::Formatter,
) -> std::fmt::Result {
match t {
DisplayFormatType::Default
| DisplayFormatType::Verbose
| DisplayFormatType::TreeRender => {
write!(f, "NeverendingOperator")
}
}
}
}
impl ExecutionPlan for NeverendingOperator {
fn name(&self) -> &str {
"NeverendingOperator"
}
fn schema(&self) -> SchemaRef {
Arc::new(Schema::empty())
}
fn properties(&self) -> &Arc<PlanProperties> {
&self.properties
}
fn children(&self) -> Vec<&Arc<dyn ExecutionPlan>> {
vec![]
}
fn apply_expressions(
&self,
_f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
) -> Result<TreeNodeRecursion> {
Ok(TreeNodeRecursion::Continue)
}
fn with_new_children(
self: Arc<Self>,
_children: Vec<Arc<dyn ExecutionPlan>>,
) -> datafusion::common::Result<Arc<dyn ExecutionPlan>> {
Ok(self)
}
fn execute(
&self,
_partition: usize,
_context: Arc<TaskContext>,
) -> datafusion::common::Result<SendableRecordBatchStream> {
Ok(Box::pin(NeverendingRecordBatchStream))
}
}
type TaskOutcome = Result<Vec<ShuffleWritePartition>, BallistaError>;
fn never_ending_executor(work_dir: &str) -> (Arc<Executor>, SessionContext) {
let executor_registration = ExecutorRegistration {
id: "executor".to_string(),
..Default::default()
};
let config_producer = Arc::new(default_config_producer);
let ctx = SessionContext::new();
let runtime_env = ctx.runtime_env().clone();
let runtime_producer: RuntimeProducer =
Arc::new(move |_| Ok(runtime_env.clone()));
let executor = Arc::new(Executor::new_basic(
executor_registration,
work_dir,
runtime_producer,
config_producer,
2,
));
(executor, ctx)
}
fn spawn_never_ending_task(
executor: &Arc<Executor>,
ctx: &SessionContext,
work_dir: &str,
key: TaskKey,
) -> tokio::sync::oneshot::Receiver<TaskOutcome> {
let shuffle_write = ShuffleWriterExec::try_new(
key.job_id.clone(),
key.stage_id,
Arc::new(NeverendingOperator::new()),
work_dir.to_string(),
)
.expect("creating shuffle writer");
let query_stage_exec =
DefaultQueryStageExec::new(ShuffleWriterVariant::Passthrough(shuffle_write));
let (sender, receiver) = tokio::sync::oneshot::channel();
let executor = executor.clone();
let task_ctx = ctx.task_ctx();
tokio::task::spawn(async move {
let task_result = executor
.execute_query_stage(key, Arc::new(query_stage_exec), task_ctx)
.await;
sender.send(task_result).expect("sending result");
});
receiver
}
async fn await_active_task_count(executor: &Executor, expected: usize) {
for _ in 0..20 {
if executor.active_task_count() == expected {
break;
} else {
tokio::time::sleep(Duration::from_millis(50)).await;
}
}
assert_eq!(executor.active_task_count(), expected);
}
async fn await_cancelled_task(receiver: tokio::sync::oneshot::Receiver<TaskOutcome>) {
tokio::time::timeout(Duration::from_secs(5), receiver)
.await
.expect("task unwinding before the timeout")
.expect("receiving task result")
.expect_err("a cancelled task fails");
}
#[tokio::test]
async fn test_task_cancellation() {
let work_dir = TempDir::new().unwrap().path().to_str().unwrap().to_string();
let (executor, ctx) = never_ending_executor(&work_dir);
let receiver = spawn_never_ending_task(
&executor,
&ctx,
&work_dir,
TaskKey {
job_id: "job-id".into(),
stage_id: 1,
task_id: 0,
},
);
await_active_task_count(&executor, 1).await;
let wake_counter = Arc::new(WakeCounter::default());
let waker = waker_ref(&wake_counter);
let mut context = Context::from_waker(&waker);
let mut tasks_drained = Box::pin(TasksDrainedFuture(executor.clone()));
assert_eq!(tasks_drained.as_mut().poll(&mut context), Poll::Pending);
assert!(
executor
.cancel_task("job-id".into(), 1, 0)
.await
.expect("cancelling task")
);
assert_eq!(executor.active_task_count(), 1);
await_cancelled_task(receiver).await;
assert_eq!(wake_counter.0.load(Ordering::SeqCst), 1);
assert_eq!(tasks_drained.as_mut().poll(&mut context), Poll::Ready(()));
}
#[tokio::test]
async fn test_tasks_drained_waits_for_last_task() {
let work_dir = TempDir::new().unwrap().path().to_str().unwrap().to_string();
let (executor, ctx) = never_ending_executor(&work_dir);
let first = spawn_never_ending_task(
&executor,
&ctx,
&work_dir,
TaskKey {
job_id: "job-id".into(),
stage_id: 1,
task_id: 0,
},
);
let second = spawn_never_ending_task(
&executor,
&ctx,
&work_dir,
TaskKey {
job_id: "job-id".into(),
stage_id: 1,
task_id: 1,
},
);
await_active_task_count(&executor, 2).await;
let wake_counter = Arc::new(WakeCounter::default());
let waker = waker_ref(&wake_counter);
let mut context = Context::from_waker(&waker);
let mut tasks_drained = Box::pin(TasksDrainedFuture(executor.clone()));
assert_eq!(tasks_drained.as_mut().poll(&mut context), Poll::Pending);
assert!(
executor
.cancel_task("job-id".into(), 1, 0)
.await
.expect("cancelling the first task")
);
await_cancelled_task(first).await;
assert_eq!(executor.active_task_count(), 1);
assert_eq!(tasks_drained.as_mut().poll(&mut context), Poll::Pending);
let wakes_before_last = wake_counter.0.load(Ordering::SeqCst);
assert!(
executor
.cancel_task("job-id".into(), 1, 1)
.await
.expect("cancelling the second task")
);
await_cancelled_task(second).await;
assert!(wake_counter.0.load(Ordering::SeqCst) > wakes_before_last);
assert_eq!(executor.active_task_count(), 0);
assert_eq!(tasks_drained.as_mut().poll(&mut context), Poll::Ready(()));
}
#[test]
fn produce_runtime_for_session_shares_read_side_state() {
let executor_registration = ExecutorRegistration {
id: "executor".to_string(),
..Default::default()
};
let config_producer = Arc::new(default_config_producer);
let base_producer: RuntimeProducer =
Arc::new(|_| Ok(Arc::new(RuntimeEnv::default())));
let identity: MemoryPoolPolicy = Arc::new(|base, _, _| Ok(base));
let cache: Arc<dyn SessionRuntimeCache> = Arc::new(
DefaultSessionRuntimeCache::new(base_producer.clone(), identity, 4),
);
let executor = Executor::new_basic(
executor_registration,
"/tmp",
base_producer,
config_producer,
2,
)
.with_session_runtime_cache(Some(cache));
let cfg = SessionConfig::new();
let e1 = executor.produce_runtime_for_session("s1", &cfg, 1).unwrap();
let e2 = executor.produce_runtime_for_session("s1", &cfg, 1).unwrap();
let e3 = executor.produce_runtime_for_session("s2", &cfg, 1).unwrap();
assert!(Arc::ptr_eq(&e1.cache_manager, &e2.cache_manager));
assert!(!Arc::ptr_eq(&e1.cache_manager, &e3.cache_manager));
}
#[test]
fn produce_runtime_for_session_falls_back_without_cache() {
let executor_registration = ExecutorRegistration {
id: "executor".to_string(),
..Default::default()
};
let config_producer = Arc::new(default_config_producer);
let base_producer: RuntimeProducer =
Arc::new(|_| Ok(Arc::new(RuntimeEnv::default())));
let executor = Executor::new_basic(
executor_registration,
"/tmp",
base_producer,
config_producer,
2,
);
let cfg = SessionConfig::new();
let e1 = executor.produce_runtime_for_session("s1", &cfg, 1).unwrap();
let e2 = executor.produce_runtime_for_session("s1", &cfg, 1).unwrap();
assert!(!Arc::ptr_eq(&e1.cache_manager, &e2.cache_manager));
}
}