Skip to content

Apache DataFusion SQL Query Engine

Support DataFrame.collect for Ballista DataFrames (#785)

Andy Groveea1d767b271c
diff --git a/ballista-examples/src/bin/ballista-dataframe.rs b/ballista-examples/src/bin/ballista-dataframe.rs
index da7d99db1c..693e67682e 100644
--- a/ballista-examples/src/bin/ballista-dataframe.rs
+++ b/ballista-examples/src/bin/ballista-dataframe.rs
@@ -38,18 +38,7 @@ async fn main() -> Result<()> {
.select_columns(&["id", "bool_col", "timestamp_col"])?
.filter(col("id").gt(lit(1)))?;
- // execute the query - note that calling collect on the DataFrame
- // trait will execute the query with DataFusion so we have to call
- // collect on the BallistaContext instead and pass it the DataFusion
- // logical plan
- let mut stream = ctx.collect(&df.to_logical_plan()).await?;
-
- // print the results
- let mut results = vec![];
- while let Some(batch) = stream.next().await {
- let batch = batch?;
- results.push(batch);
- }
+ let results = df.collect().await?;
pretty::print_batches(&results)?;
Ok(())
diff --git a/ballista-examples/src/bin/ballista-sql.rs b/ballista-examples/src/bin/ballista-sql.rs
index f9e7d180af..590ab7bcf7 100644
--- a/ballista-examples/src/bin/ballista-sql.rs
+++ b/ballista-examples/src/bin/ballista-sql.rs
@@ -45,18 +45,7 @@ async fn main() -> Result<()> {
GROUP BY c1",
)?;
- // execute the query - note that calling collect on the DataFrame
- // trait will execute the query with DataFusion so we have to call
- // collect on the BallistaContext instead and pass it the DataFusion
- // logical plan
- let mut stream = ctx.collect(&df.to_logical_plan()).await?;
-
- // print the results
- let mut results = vec![];
- while let Some(batch) = stream.next().await {
- let batch = batch?;
- results.push(batch);
- }
+ let results = df.collect().await?;
pretty::print_batches(&results)?;
Ok(())
diff --git a/ballista/rust/client/src/context.rs b/ballista/rust/client/src/context.rs
index 26087f8e66..16a90b2e27 100644
--- a/ballista/rust/client/src/context.rs
+++ b/ballista/rust/client/src/context.rs
@@ -17,32 +17,19 @@
//! Distributed execution context.
+use std::collections::HashMap;
+use std::fs;
use std::path::PathBuf;
-use std::pin::Pin;
use std::sync::{Arc, Mutex};
-use std::{collections::HashMap, convert::TryInto};
-use std::{fs, time::Duration};
use ballista_core::config::BallistaConfig;
-use ballista_core::serde::protobuf::{
- execute_query_params::Query, job_status, scheduler_grpc_client::SchedulerGrpcClient,
- ExecuteQueryParams, GetJobStatusParams, GetJobStatusResult, KeyValuePair,
- PartitionLocation,
-};
-use ballista_core::{
- client::BallistaClient, datasource::DfTableAdapter, utils::create_datafusion_context,
- utils::WrappedStream,
-};
+use ballista_core::{datasource::DfTableAdapter, utils::create_datafusion_context};
-use datafusion::arrow::datatypes::Schema;
use datafusion::catalog::TableReference;
-use datafusion::error::{DataFusionError, Result};
+use datafusion::dataframe::DataFrame;
+use datafusion::error::Result;
use datafusion::logical_plan::LogicalPlan;
use datafusion::physical_plan::csv::CsvReadOptions;
-use datafusion::{dataframe::DataFrame, physical_plan::RecordBatchStream};
-use futures::future;
-use futures::StreamExt;
-use log::{error, info};
struct BallistaContextState {
/// Ballista configuration
@@ -142,7 +129,12 @@ impl BallistaContext {
let path = fs::canonicalize(&path)?;
// use local DataFusion context for now but later this might call the scheduler
- let mut ctx = create_datafusion_context(&self.state.lock().unwrap().config());
+ let guard = self.state.lock().unwrap();
+ let mut ctx = create_datafusion_context(
+ &guard.scheduler_host,
+ guard.scheduler_port,
+ &guard.config(),
+ );
let df = ctx.read_parquet(path.to_str().unwrap())?;
Ok(df)
}
@@ -159,7 +151,12 @@ impl BallistaContext {
let path = fs::canonicalize(&path)?;
// use local DataFusion context for now but later this might call the scheduler
- let mut ctx = create_datafusion_context(&self.state.lock().unwrap().config());
+ let guard = self.state.lock().unwrap();
+ let mut ctx = create_datafusion_context(
+ &guard.scheduler_host,
+ guard.scheduler_port,
+ &guard.config(),
+ );
let df = ctx.read_csv(path.to_str().unwrap(), options)?;
Ok(df)
}
@@ -193,7 +190,11 @@ impl BallistaContext {
// use local DataFusion context for now but later this might call the scheduler
// register tables
let state = self.state.lock().unwrap();
- let mut ctx = create_datafusion_context(&state.config());
+ let mut ctx = create_datafusion_context(
+ &state.scheduler_host,
+ state.scheduler_port,
+ state.config(),
+ );
for (name, plan) in &state.tables {
let plan = ctx.optimize(plan)?;
let execution_plan = ctx.create_physical_plan(&plan)?;
@@ -204,126 +205,6 @@ impl BallistaContext {
}
ctx.sql(sql)
}
-
- async fn fetch_partition(
- location: PartitionLocation,
- ) -> Result<Pin<Box<dyn RecordBatchStream + Send + Sync>>> {
- let metadata = location.executor_meta.ok_or_else(|| {
- DataFusionError::Internal("Received empty executor metadata".to_owned())
- })?;
- let partition_id = location.partition_id.ok_or_else(|| {
- DataFusionError::Internal("Received empty partition id".to_owned())
- })?;
- let mut ballista_client =
- BallistaClient::try_new(metadata.host.as_str(), metadata.port as u16)
- .await
- .map_err(|e| DataFusionError::Execution(format!("{:?}", e)))?;
- Ok(ballista_client
- .fetch_partition(
- &partition_id.job_id,
- partition_id.stage_id as usize,
- partition_id.partition_id as usize,
- &location.path,
- )
- .await
- .map_err(|e| DataFusionError::Execution(format!("{:?}", e)))?)
- }
-
- pub async fn collect(
- &self,
- plan: &LogicalPlan,
- ) -> Result<Pin<Box<dyn RecordBatchStream + Send + Sync>>> {
- let (scheduler_url, config) = {
- let state = self.state.lock().unwrap();
- let scheduler_url =
- format!("http://{}:{}", state.scheduler_host, state.scheduler_port);
- (scheduler_url, state.config.clone())
- };
-
- info!("Connecting to Ballista scheduler at {}", scheduler_url);
-
- let mut scheduler = SchedulerGrpcClient::connect(scheduler_url)
- .await
- .map_err(|e| DataFusionError::Execution(format!("{:?}", e)))?;
-
- let schema: Schema = plan.schema().as_ref().clone().into();
-
- let job_id = scheduler
- .execute_query(ExecuteQueryParams {
- query: Some(Query::LogicalPlan(
- (plan)
- .try_into()
- .map_err(|e| DataFusionError::Execution(format!("{:?}", e)))?,
- )),
- settings: config
- .settings()
- .iter()
- .map(|(k, v)| KeyValuePair {
- key: k.to_owned(),
- value: v.to_owned(),
- })
- .collect::<Vec<_>>(),
- })
- .await
- .map_err(|e| DataFusionError::Execution(format!("{:?}", e)))?
- .into_inner()
- .job_id;
-
- let mut prev_status: Option<job_status::Status> = None;
-
- loop {
- let GetJobStatusResult { status } = scheduler
- .get_job_status(GetJobStatusParams {
- job_id: job_id.clone(),
- })
- .await
- .map_err(|e| DataFusionError::Execution(format!("{:?}", e)))?
- .into_inner();
- let status = status.and_then(|s| s.status).ok_or_else(|| {
- DataFusionError::Internal("Received empty status message".to_owned())
- })?;
- let wait_future = tokio::time::sleep(Duration::from_millis(100));
- let has_status_change = prev_status.map(|x| x != status).unwrap_or(true);
- match status {
- job_status::Status::Queued(_) => {
- if has_status_change {
- info!("Job {} still queued...", job_id);
- }
- wait_future.await;
- prev_status = Some(status);
- }
- job_status::Status::Running(_) => {
- if has_status_change {
- info!("Job {} is running...", job_id);
- }
- wait_future.await;
- prev_status = Some(status);
- }
- job_status::Status::Failed(err) => {
- let msg = format!("Job {} failed: {}", job_id, err.error);
- error!("{}", msg);
- break Err(DataFusionError::Execution(msg));
- }
- job_status::Status::Completed(completed) => {
- let result = future::join_all(
- completed
- .partition_location
- .into_iter()
- .map(BallistaContext::fetch_partition),
- )
- .await
- .into_iter()
- .collect::<Result<Vec<_>>>()?;
-
- let result = WrappedStream::new(
- Box::pin(futures::stream::iter(result).flatten()),
- Arc::new(schema),
- );
- break Ok(Box::pin(result));
- }
- };
- }
- }
}
#[cfg(test)]
diff --git a/ballista/rust/core/src/execution_plans/distributed_query.rs b/ballista/rust/core/src/execution_plans/distributed_query.rs
new file mode 100644
index 0000000000..8abfe66788
--- /dev/null
+++ b/ballista/rust/core/src/execution_plans/distributed_query.rs
@@ -0,0 +1,213 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::any::Any;
+use std::convert::TryInto;
+use std::pin::Pin;
+use std::sync::Arc;
+use std::time::Duration;
+
+use crate::client::BallistaClient;
+use crate::config::BallistaConfig;
+use crate::serde::protobuf::{
+ execute_query_params::Query, job_status, scheduler_grpc_client::SchedulerGrpcClient,
+ ExecuteQueryParams, GetJobStatusParams, GetJobStatusResult, KeyValuePair,
+ PartitionLocation,
+};
+use crate::utils::WrappedStream;
+
+use datafusion::arrow::datatypes::{Schema, SchemaRef};
+use datafusion::error::{DataFusionError, Result};
+use datafusion::logical_plan::LogicalPlan;
+use datafusion::physical_plan::{
+ ExecutionPlan, Partitioning, RecordBatchStream, SendableRecordBatchStream,
+};
+
+use async_trait::async_trait;
+use futures::future;
+use futures::StreamExt;
+use log::{error, info};
+
+/// This operator sends a logial plan to a Ballista scheduler for execution and
+/// polls the scheduler until the query is complete and then fetches the resulting
+/// batches directly from the executors that hold the results from the final
+/// query stage.
+#[derive(Debug, Clone)]
+pub struct DistributedQueryExec {
+ /// Ballista scheduler URL
+ scheduler_url: String,
+ /// Ballista configuration
+ config: BallistaConfig,
+ /// Logical plan to execute
+ plan: LogicalPlan,
+}
+
+impl DistributedQueryExec {
+ pub fn new(scheduler_url: String, config: BallistaConfig, plan: LogicalPlan) -> Self {
+ Self {
+ scheduler_url,
+ config,
+ plan,
+ }
+ }
+}
+
+#[async_trait]
+impl ExecutionPlan for DistributedQueryExec {
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn schema(&self) -> SchemaRef {
+ self.plan.schema().as_ref().clone().into()
+ }
+
+ fn output_partitioning(&self) -> Partitioning {
+ Partitioning::UnknownPartitioning(1)
+ }
+
+ fn children(&self) -> Vec<Arc<dyn ExecutionPlan>> {
+ vec![]
+ }
+
+ fn with_new_children(
+ &self,
+ _children: Vec<Arc<dyn ExecutionPlan>>,
+ ) -> datafusion::error::Result<Arc<dyn ExecutionPlan>> {
+ Ok(Arc::new(DistributedQueryExec::new(
+ self.scheduler_url.clone(),
+ self.config.clone(),
+ self.plan.clone(),
+ )))
+ }
+
+ async fn execute(
+ &self,
+ partition: usize,
+ ) -> datafusion::error::Result<SendableRecordBatchStream> {
+ assert_eq!(0, partition);
+
+ info!("Connecting to Ballista scheduler at {}", self.scheduler_url);
+
+ let mut scheduler = SchedulerGrpcClient::connect(self.scheduler_url.clone())
+ .await
+ .map_err(|e| DataFusionError::Execution(format!("{:?}", e)))?;
+
+ let schema: Schema = self.plan.schema().as_ref().clone().into();
+
+ let job_id = scheduler
+ .execute_query(ExecuteQueryParams {
+ query: Some(Query::LogicalPlan(
+ (&self.plan)
+ .try_into()
+ .map_err(|e| DataFusionError::Execution(format!("{:?}", e)))?,
+ )),
+ settings: self
+ .config
+ .settings()
+ .iter()
+ .map(|(k, v)| KeyValuePair {
+ key: k.to_owned(),
+ value: v.to_owned(),
+ })
+ .collect::<Vec<_>>(),
+ })
+ .await
+ .map_err(|e| DataFusionError::Execution(format!("{:?}", e)))?
+ .into_inner()
+ .job_id;
+
+ let mut prev_status: Option<job_status::Status> = None;
+
+ loop {
+ let GetJobStatusResult { status } = scheduler
+ .get_job_status(GetJobStatusParams {
+ job_id: job_id.clone(),
+ })
+ .await
+ .map_err(|e| DataFusionError::Execution(format!("{:?}", e)))?
+ .into_inner();
+ let status = status.and_then(|s| s.status).ok_or_else(|| {
+ DataFusionError::Internal("Received empty status message".to_owned())
+ })?;
+ let wait_future = tokio::time::sleep(Duration::from_millis(100));
+ let has_status_change = prev_status.map(|x| x != status).unwrap_or(true);
+ match status {
+ job_status::Status::Queued(_) => {
+ if has_status_change {
+ info!("Job {} still queued...", job_id);
+ }
+ wait_future.await;
+ prev_status = Some(status);
+ }
+ job_status::Status::Running(_) => {
+ if has_status_change {
+ info!("Job {} is running...", job_id);
+ }
+ wait_future.await;
+ prev_status = Some(status);
+ }
+ job_status::Status::Failed(err) => {
+ let msg = format!("Job {} failed: {}", job_id, err.error);
+ error!("{}", msg);
+ break Err(DataFusionError::Execution(msg));
+ }
+ job_status::Status::Completed(completed) => {
+ let result = future::join_all(
+ completed
+ .partition_location
+ .into_iter()
+ .map(fetch_partition),
+ )
+ .await
+ .into_iter()
+ .collect::<Result<Vec<_>>>()?;
+
+ let result = WrappedStream::new(
+ Box::pin(futures::stream::iter(result).flatten()),
+ Arc::new(schema),
+ );
+ break Ok(Box::pin(result));
+ }
+ };
+ }
+ }
+}
+
+async fn fetch_partition(
+ location: PartitionLocation,
+) -> Result<SendableRecordBatchStream> {
+ let metadata = location.executor_meta.ok_or_else(|| {
+ DataFusionError::Internal("Received empty executor metadata".to_owned())
+ })?;
+ let partition_id = location.partition_id.ok_or_else(|| {
+ DataFusionError::Internal("Received empty partition id".to_owned())
+ })?;
+ let mut ballista_client =
+ BallistaClient::try_new(metadata.host.as_str(), metadata.port as u16)
+ .await
+ .map_err(|e| DataFusionError::Execution(format!("{:?}", e)))?;
+ Ok(ballista_client
+ .fetch_partition(
+ &partition_id.job_id,
+ partition_id.stage_id as usize,
+ partition_id.partition_id as usize,
+ &location.path,
+ )
+ .await
+ .map_err(|e| DataFusionError::Execution(format!("{:?}", e)))?)
+}
diff --git a/ballista/rust/core/src/execution_plans/mod.rs b/ballista/rust/core/src/execution_plans/mod.rs
index ca4e60023c..b10ff341e9 100644
--- a/ballista/rust/core/src/execution_plans/mod.rs
+++ b/ballista/rust/core/src/execution_plans/mod.rs
@@ -18,10 +18,12 @@
//! This module contains execution plans that are needed to distribute Datafusion's execution plans into
//! several Ballista executors.
+mod distributed_query;
mod shuffle_reader;
mod shuffle_writer;
mod unresolved_shuffle;
+pub use distributed_query::DistributedQueryExec;
pub use shuffle_reader::ShuffleReaderExec;
pub use shuffle_writer::ShuffleWriterExec;
pub use unresolved_shuffle::UnresolvedShuffleExec;
diff --git a/ballista/rust/core/src/utils.rs b/ballista/rust/core/src/utils.rs
index 8b1cf61a55..4187faa664 100644
--- a/ballista/rust/core/src/utils.rs
+++ b/ballista/rust/core/src/utils.rs
@@ -23,7 +23,9 @@ use std::sync::Arc;
use std::{fs::File, pin::Pin};
use crate::error::{BallistaError, Result};
-use crate::execution_plans::{ShuffleWriterExec, UnresolvedShuffleExec};
+use crate::execution_plans::{
+ DistributedQueryExec, ShuffleWriterExec, UnresolvedShuffleExec,
+};
use crate::memory_stream::MemoryStream;
use crate::serde::scheduler::PartitionStats;
@@ -38,8 +40,11 @@ use datafusion::arrow::{
ipc::writer::FileWriter,
record_batch::RecordBatch,
};
-use datafusion::execution::context::{ExecutionConfig, ExecutionContext};
-use datafusion::logical_plan::Operator;
+use datafusion::error::DataFusionError;
+use datafusion::execution::context::{
+ ExecutionConfig, ExecutionContext, ExecutionContextState, QueryPlanner,
+};
+use datafusion::logical_plan::{LogicalPlan, Operator};
use datafusion::physical_optimizer::coalesce_batches::CoalesceBatches;
use datafusion::physical_optimizer::merge_exec::AddCoalescePartitionsExec;
use datafusion::physical_optimizer::optimizer::PhysicalOptimizerRule;
@@ -232,12 +237,49 @@ fn build_exec_plan_diagram(
}
/// Create a DataFusion context that is compatible with Ballista
-pub fn create_datafusion_context(config: &BallistaConfig) -> ExecutionContext {
- let config =
- ExecutionConfig::new().with_concurrency(config.default_shuffle_partitions());
+pub fn create_datafusion_context(
+ scheduler_host: &str,
+ scheduler_port: u16,
+ config: &BallistaConfig,
+) -> ExecutionContext {
+ let scheduler_url = format!("http://{}:{}", scheduler_host, scheduler_port);
+ let config = ExecutionConfig::new()
+ .with_query_planner(Arc::new(BallistaQueryPlanner::new(
+ scheduler_url,
+ config.clone(),
+ )))
+ .with_concurrency(config.default_shuffle_partitions());
ExecutionContext::with_config(config)
}
+pub struct BallistaQueryPlanner {
+ scheduler_url: String,
+ config: BallistaConfig,
+}
+
+impl BallistaQueryPlanner {
+ pub fn new(scheduler_url: String, config: BallistaConfig) -> Self {
+ Self {
+ scheduler_url,
+ config,
+ }
+ }
+}
+
+impl QueryPlanner for BallistaQueryPlanner {
+ fn create_physical_plan(
+ &self,
+ logical_plan: &LogicalPlan,
+ _ctx_state: &ExecutionContextState,
+ ) -> std::result::Result<Arc<dyn ExecutionPlan>, DataFusionError> {
+ Ok(Arc::new(DistributedQueryExec::new(
+ self.scheduler_url.clone(),
+ self.config.clone(),
+ logical_plan.clone(),
+ )))
+ }
+}
+
pub struct WrappedStream {
stream: Pin<Box<dyn Stream<Item = ArrowResult<RecordBatch>> + Send + Sync>>,
schema: SchemaRef,
diff --git a/ballista/rust/scheduler/src/lib.rs b/ballista/rust/scheduler/src/lib.rs
index f5e2dc1dfd..3e4e73586d 100644
--- a/ballista/rust/scheduler/src/lib.rs
+++ b/ballista/rust/scheduler/src/lib.rs
@@ -82,8 +82,8 @@ use self::state::{ConfigBackendClient, SchedulerState};
use ballista_core::config::BallistaConfig;
use ballista_core::execution_plans::ShuffleWriterExec;
use ballista_core::serde::scheduler::to_proto::hash_partitioning_to_proto;
-use ballista_core::utils::create_datafusion_context;
use datafusion::physical_plan::parquet::ParquetExec;
+use datafusion::prelude::{ExecutionConfig, ExecutionContext};
use std::time::{Instant, SystemTime, UNIX_EPOCH};
#[derive(Clone)]
@@ -511,6 +511,13 @@ impl SchedulerGrpc for SchedulerServer {
}
}
+/// Create a DataFusion context that is compatible with Ballista
+pub fn create_datafusion_context(config: &BallistaConfig) -> ExecutionContext {
+ let config =
+ ExecutionConfig::new().with_concurrency(config.default_shuffle_partitions());
+ ExecutionContext::with_config(config)
+}
+
#[cfg(all(test, feature = "sled"))]
mod test {
use std::{
diff --git a/benchmarks/src/bin/tpch.rs b/benchmarks/src/bin/tpch.rs
index 169319d30b..08b8864acd 100644
--- a/benchmarks/src/bin/tpch.rs
+++ b/benchmarks/src/bin/tpch.rs
@@ -25,8 +25,6 @@ use std::{
time::Instant,
};
-use futures::StreamExt;
-
use ballista::context::BallistaContext;
use ballista::prelude::{BallistaConfig, BALLISTA_DEFAULT_SHUFFLE_PARTITIONS};
@@ -312,15 +310,10 @@ async fn benchmark_ballista(opt: BallistaBenchmarkOpt) -> Result<()> {
let df = ctx
.sql(&sql)
.map_err(|e| DataFusionError::Plan(format!("{:?}", e)))?;
- let mut batches = vec![];
- let mut stream = ctx
- .collect(&df.to_logical_plan())
+ let batches = df
+ .collect()
.await
.map_err(|e| DataFusionError::Plan(format!("{:?}", e)))?;
- while let Some(result) = stream.next().await {
- let batch = result?;
- batches.push(batch);
- }
let elapsed = start.elapsed().as_secs_f64() * 1000.0;
millis.push(elapsed as f64);
println!("Query {} iteration {} took {:.1} ms", opt.query, i, elapsed);