Skip to main content

ballista_executor/
lib.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18#![doc = include_str!("../README.md")]
19#![warn(missing_docs)]
20
21/// Connection pool for `BallistaClient` instances.
22mod client_pool;
23/// Execution plan for collecting distributed query results into a single partition.
24pub mod collect;
25/// Command-line configuration for the executor binary.
26#[cfg(feature = "build-binary")]
27pub mod config;
28/// Extension point for custom query stage execution engines.
29pub mod execution_engine;
30/// Pull-based task execution loop that polls the scheduler for work.
31pub mod execution_loop;
32/// Core executor implementation for running distributed query tasks.
33pub mod executor;
34/// Executor process lifecycle management and configuration.
35pub mod executor_process;
36/// gRPC server for receiving pushed tasks from the scheduler.
37pub mod executor_server;
38/// Arrow Flight service for streaming shuffle data between executors.
39pub mod flight_service;
40/// HTTP server for Kubernetes-style /healthz and /readyz probes.
41pub mod health;
42/// Metrics collection for executor runtime statistics.
43pub mod metrics;
44/// Session-scoped cache of shared executor runtime environments.
45pub mod runtime_cache;
46/// Graceful shutdown coordination for executor components.
47pub mod shutdown;
48/// Signal handling for process termination.
49pub mod terminate;
50
51mod cpu_bound_executor;
52mod standalone;
53
54use ballista_core::error::BallistaError;
55use log::debug;
56use std::net::SocketAddr;
57
58pub use standalone::new_standalone_executor;
59pub use standalone::new_standalone_executor_from_builder;
60pub use standalone::new_standalone_executor_from_state;
61
62use crate::shutdown::Shutdown;
63use ballista_core::serde::protobuf::{
64    FailedTask, OperatorMetricsSet, RuntimeStatsReport, ShuffleWritePartition,
65    SuccessfulTask, TaskColumnStats, TaskStatus, WindowStateReport, task_status,
66};
67use ballista_core::serde::scheduler::TaskKey;
68use ballista_core::utils::GrpcServerConfig;
69use log::info;
70
71/// [ArrowFlightServerProvider] provides a function which creates a new Arrow Flight server.
72///
73/// The function should take four arguments:
74/// [String] - executor work directory
75/// [SocketAddr] - the address to bind the server to
76/// [Shutdown] - a shutdown signal to gracefully shutdown the server
77/// [GrpcServerConfig] - the gRPC server configuration for timeout settings
78/// Returns a [tokio::task::JoinHandle] which will be registered as service handler
79///
80pub type ArrowFlightServerProvider = dyn Fn(
81        String,
82        SocketAddr,
83        Shutdown,
84        GrpcServerConfig,
85    ) -> tokio::task::JoinHandle<Result<(), BallistaError>>
86    + Send
87    + Sync;
88
89/// Timestamps capturing the lifecycle of a task execution.
90#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
91pub struct TaskExecutionTimes {
92    /// Timestamp when the task was launched by the scheduler (milliseconds since epoch).
93    launch_time: u64,
94    /// Timestamp when task execution started on the executor (milliseconds since epoch).
95    start_exec_time: u64,
96    /// Timestamp when task execution completed (milliseconds since epoch).
97    end_exec_time: u64,
98}
99
100/// Side-channel data harvested from a task's executed plan, attached to the
101/// [`TaskStatus`] reported to the scheduler on success.
102///
103/// Marked `#[non_exhaustive]` so future additions (e.g. tracing IDs, further
104/// runtime reports) are non-breaking for external callers that construct via
105/// `TaskCompletionExtras { operator_metrics: …, ..Default::default() }`.
106#[derive(Debug, Clone, Default)]
107#[non_exhaustive]
108pub struct TaskCompletionExtras {
109    /// Per-operator metrics collected from the executed plan.
110    pub operator_metrics: Option<Vec<OperatorMetricsSet>>,
111    /// Runtime-stats reports harvested from `RuntimeStatsExec` taps in the plan.
112    pub runtime_stats: Vec<RuntimeStatsReport>,
113    /// Finalized window-aggregate state captured by an ever-expanding-frame
114    /// window, already stamped with the global partition each entry belongs
115    /// to by the stage's `ShuffleWriterExec`.
116    pub window_state: Vec<WindowStateReport>,
117    /// Per-column statistics folded across this task's shuffle output. Empty
118    /// when the executed plan collects none (e.g. non-sort shuffle paths).
119    pub column_stats: Vec<TaskColumnStats>,
120}
121
122/// Converts a task execution result into a [`TaskStatus`] protobuf message.
123///
124/// This function wraps the outcome of task execution (success or failure)
125/// along with timing and metrics information into a status message that
126/// can be sent back to the scheduler.
127pub fn as_task_status(
128    execution_result: Result<Vec<ShuffleWritePartition>, BallistaError>,
129    executor_id: String,
130    stage_attempt_num: usize,
131    key: TaskKey,
132    execution_times: TaskExecutionTimes,
133    extras: TaskCompletionExtras,
134) -> TaskStatus {
135    let TaskCompletionExtras {
136        operator_metrics,
137        runtime_stats,
138        window_state,
139        column_stats,
140    } = extras;
141    let metrics = operator_metrics.unwrap_or_default();
142    let task_id = key.task_id;
143    match execution_result {
144        Ok(partitions) => {
145            debug!(
146                "Task {task_id} finished with operator_metrics array size {} \
147                 and {} runtime-stats report(s), {} window-state report(s)",
148                metrics.len(),
149                runtime_stats.len(),
150                window_state.len(),
151            );
152            TaskStatus {
153                task_id: task_id as u32,
154                job_id: key.job_id.clone().into(),
155                stage_id: key.stage_id as u32,
156                stage_attempt_num: stage_attempt_num as u32,
157                launch_time: execution_times.launch_time,
158                start_exec_time: execution_times.start_exec_time,
159                end_exec_time: execution_times.end_exec_time,
160                metrics,
161                status: Some(task_status::Status::Successful(SuccessfulTask {
162                    executor_id,
163                    partitions,
164                    runtime_stats,
165                    task_column_stats: column_stats,
166                    window_state,
167                })),
168            }
169        }
170        Err(e) => {
171            let error_msg = e.to_string();
172            info!("Task {task_id} failed: {error_msg}");
173
174            TaskStatus {
175                task_id: task_id as u32,
176                job_id: key.job_id.clone().into(),
177                stage_id: key.stage_id as u32,
178                stage_attempt_num: stage_attempt_num as u32,
179                launch_time: execution_times.launch_time,
180                start_exec_time: execution_times.start_exec_time,
181                end_exec_time: execution_times.end_exec_time,
182                metrics,
183                status: Some(task_status::Status::Failed(FailedTask::from(e))),
184            }
185        }
186    }
187}