Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
191 changes: 104 additions & 87 deletions Cargo.lock

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ rdkafka = { version = "0.39.0", optional = true, features = [
"tracing",
"libz-static",
] }
sasl2-sys = { version = "0.1.22+2.1.28", optional = true, features = ["vendored"] }
sasl2-sys = { version = "0.1.22", optional = true, features = ["vendored"] }
# AWS MSK IAM authentication for Kafka (SASL/OAUTHBEARER token signing)
aws-msk-iam-sasl-signer = { version = "1.0.2", optional = true }
aws-types = { version = "1.7.0", optional = true }
Expand Down Expand Up @@ -204,6 +204,7 @@ tikv-jemallocator = { version = "0.7.0", features = [
"background_threads",
] }
tikv-jemalloc-ctl = { version = "0.7.0", features = ["stats"] }
tikv-jemalloc-sys = "0.7.1"

[build-dependencies]
cargo_toml = "0.22.3"
Expand Down
2 changes: 1 addition & 1 deletion src/alerts/alerts_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ async fn execute_local_query(
filter_tag: None,
};

let (records, _) = execute(query, false, tenant_id)
let (records, _, _query_admission) = execute(query, false, tenant_id)
.await
.map_err(|err| AlertError::CustomError(format!("Failed to execute query: {err}")))?;

Expand Down
70 changes: 67 additions & 3 deletions src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@
*/

use clap::{Parser, value_parser};
use std::{env, fs, ops::Mul, path::PathBuf};
use std::{env, fs, path::PathBuf};
use sysinfo::System;

use url::Url;

Expand All @@ -37,6 +38,41 @@ pub const DEFAULT_PASSWORD: &str = "admin";

pub const DATASET_FIELD_COUNT_LIMIT: usize = 1000;
const DEFAULT_PARQUET_METADATA_CACHE_SIZE: usize = 50 * 1024 * 1024; // 50 MB
pub(crate) const DEFAULT_MAX_CONCURRENT_QUERIES: u32 = 5;
const MEMORY_PER_TARGET_PARTITION: u64 = 256 * 1024 * 1024;

fn target_partitions_for_resources(cpus: usize, total_memory: u64) -> u64 {
let cpu_limit = cpus.saturating_mul(4).max(1);
let memory_limit = (total_memory / MEMORY_PER_TARGET_PARTITION).max(1) as usize;
cpu_limit.min(memory_limit) as u64
}

pub(crate) fn detected_memory_limit() -> u64 {
let mut system = System::new();
system.refresh_memory();

let cgroup_file_limit = [
"/sys/fs/cgroup/memory.max",
"/sys/fs/cgroup/memory/memory.limit_in_bytes",
]
.into_iter()
.find_map(|path| fs::read_to_string(path).ok()?.trim().parse::<u64>().ok());

[
Some(system.total_memory()),
system.cgroup_limits().map(|cgroup| cgroup.total_memory),
cgroup_file_limit,
]
.into_iter()
.flatten()
.filter(|limit| *limit > 0)
.min()
.unwrap_or_else(|| system.total_memory())
}

fn default_target_partitions() -> u64 {
target_partitions_for_resources(num_cpus::get(), detected_memory_limit())
}
#[derive(Parser)]
#[command(
name = "parseable",
Expand Down Expand Up @@ -222,7 +258,7 @@ pub struct Options {
#[arg(
long,
env = "P_DATAFUSION_TARGET_PARTITIONS",
default_value_t = num_cpus::get().mul(4).max(1) as u64,
default_value_t = default_target_partitions(),
value_parser = value_parser!(u64).range(1..),
help = "Number of partitions for DF to split execution into"
)]
Expand Down Expand Up @@ -463,6 +499,15 @@ pub struct Options {
)]
pub query_memory_pool_size: Option<usize>,

#[arg(
long,
env = "P_MAX_CONCURRENT_QUERIES",
default_value = "5",
value_parser = value_parser!(u32).range(1..),
help = "Maximum number of queries that can execute concurrently"
)]
pub max_concurrent_queries: Option<u32>,

#[arg(
long,
env = "P_PARQUET_METADATA_CACHE_SIZE",
Expand All @@ -484,7 +529,7 @@ pub struct Options {
#[arg(
long,
env = "P_EXECUTION_BATCH_SIZE",
default_value = "20000",
default_value = "8192",
help = "batch size for query execution"
)]
pub execution_batch_size: usize,
Expand Down Expand Up @@ -898,3 +943,22 @@ impl Options {
})
}
}

#[cfg(test)]
mod tests {
use super::target_partitions_for_resources;

#[test]
fn target_partitions_are_bounded_by_memory() {
assert_eq!(target_partitions_for_resources(16, 1024 * 1024 * 1024), 4);
assert_eq!(
target_partitions_for_resources(16, 16 * 1024 * 1024 * 1024),
64
);
}

#[test]
fn target_partitions_never_reach_zero() {
assert_eq!(target_partitions_for_resources(0, 0), 1);
}
}
34 changes: 29 additions & 5 deletions src/handlers/airplane.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ use arrow_flight::PollInfo;
use arrow_flight::flight_service_server::FlightServiceServer;
use arrow_schema::ArrowError;
use std::net::SocketAddr;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use std::time::Instant;
use tonic::codec::CompressionEncoding;
use tracing::{error, info};
Expand All @@ -33,8 +36,8 @@ use crate::handlers::http::query::into_query;
use crate::handlers::livetail::cross_origin_config;
use crate::metrics::QUERY_EXECUTE_TIME;
use crate::parseable::{DEFAULT_TENANT, PARSEABLE};
use crate::query::{QUERY_SESSION, execute, resolve_stream_names};
use crate::utils::arrow::flight::{get_query_from_ticket, into_flight_data};
use crate::query::{QUERY_SESSION, QueryAdmissionGuard, execute, resolve_stream_names};
use crate::utils::arrow::flight::{DoGetStream, get_query_from_ticket, into_flight_data};
use crate::utils::time::TimeRange;
use crate::utils::{get_tenant_id_from_key, user_auth_for_datasets};
use arrow_flight::{
Expand All @@ -43,7 +46,7 @@ use arrow_flight::{
flight_service_server::FlightService,
};
use arrow_ipc::writer::IpcWriteOptions;
use futures::stream;
use futures::{Stream, stream};
use tonic::{Request, Response, Status, Streaming};

use crate::handlers::livetail::extract_session_key;
Expand All @@ -53,6 +56,19 @@ use crate::rbac::Users;
#[derive(Clone, Debug)]
pub struct AirServiceImpl {}

struct AdmissionGuardedFlightStream<S> {
inner: S,
_query_admission: Arc<QueryAdmissionGuard>,
}

impl<S: Stream + Unpin> Stream for AdmissionGuardedFlightStream<S> {
type Item = S::Item;

fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
Pin::new(&mut self.inner).poll_next(cx)
}
}

#[tonic::async_trait]
impl FlightService for AirServiceImpl {
type HandshakeStream = stream::BoxStream<'static, Result<HandshakeResponse, Status>>;
Expand Down Expand Up @@ -193,7 +209,7 @@ impl FlightService for AirServiceImpl {
})?;
let time = Instant::now();

let (records, _) = execute(query, false, &None)
let (records, _, query_admission) = execute(query, false, &None)
.await
.map_err(|err| Status::internal(err.to_string()))?;

Expand All @@ -218,7 +234,15 @@ impl FlightService for AirServiceImpl {
let schema = Schema::try_merge(schemas).map_err(|err| Status::internal(err.to_string()))?;
*/
// Taxi out airplane
let out = into_flight_data(records);
query_admission.stop_memory_pressure_monitor();
let out = into_flight_data(records).map(|response| {
response.map(|stream| {
Box::pin(AdmissionGuardedFlightStream {
inner: stream,
_query_admission: query_admission,
}) as DoGetStream
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
})
});

let time = time.elapsed().as_secs_f64();
let tenant_id = get_tenant_id_from_key(&key);
Expand Down
3 changes: 3 additions & 0 deletions src/handlers/http/modal/ssl_acceptor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ pub fn get_ssl_acceptor(
) -> anyhow::Result<Option<ServerConfig>> {
match (tls_cert, tls_key) {
(Some(cert), Some(key)) => {
// Keep this consistent with the process-wide Ring provider installed
// in main. Rustls has no non-deprecated Ring provider constructor.
#[allow(deprecated)]
let provider = Arc::new(rustls::crypto::ring::default_provider());
let server_config = ServerConfig::builder_with_provider(provider)
.with_safe_default_protocol_versions()?
Expand Down
58 changes: 48 additions & 10 deletions src/handlers/http/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ use serde_json::{Value, json};
use std::collections::HashMap;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use std::time::Instant;
use tokio::task::JoinSet;
use tracing::{error, info, warn};
Expand All @@ -50,7 +51,9 @@ use crate::metrics::{QUERY_EXECUTE_TIME, increment_query_calls_by_date};
use crate::parseable::{DEFAULT_TENANT, PARSEABLE, StreamNotFound};
use crate::query::error::ExecuteError;
use crate::query::resolve_stream_names;
use crate::query::{CountsRecord, CountsRequest, QUERY_SESSION, Query as LogicalQuery, execute};
use crate::query::{
CountsRecord, CountsRequest, QUERY_SESSION, Query as LogicalQuery, QueryAdmissionGuard, execute,
};
use crate::rbac::Users;
use crate::response::QueryResponse;
use crate::storage::ObjectStorageError;
Expand Down Expand Up @@ -83,7 +86,14 @@ pub async fn get_records_and_fields(
query_request: &Query,
creds: &SessionKey,
tenant_id: &Option<String>,
) -> Result<(Option<Vec<RecordBatch>>, Option<Vec<String>>), QueryError> {
) -> Result<
(
Option<Vec<RecordBatch>>,
Option<Vec<String>>,
Arc<QueryAdmissionGuard>,
),
QueryError,
> {
let mut session_state = QUERY_SESSION.get_ctx().state();
let time_range =
TimeRange::parse_human_time(&query_request.start_time, &query_request.end_time)?;
Expand All @@ -103,7 +113,7 @@ pub async fn get_records_and_fields(

user_auth_for_datasets(&permissions, &tables, tenant_id).await?;

let (records, fields) = execute(query, false, tenant_id).await?;
let (records, fields, query_admission) = execute(query, false, tenant_id).await?;

let records = match records {
Either::Left(vec_rb) => vec_rb,
Expand All @@ -112,7 +122,7 @@ pub async fn get_records_and_fields(
}
};

Ok((Some(records), Some(fields)))
Ok((Some(records), Some(fields), query_admission))
}

/// Executes a query after the caller has already loaded and authorized the streams.
Expand All @@ -123,7 +133,14 @@ pub async fn get_records_and_fields_for_authorized_query(
query_request: &Query,
authorized_tables: &[String],
tenant_id: &Option<String>,
) -> Result<(Option<Vec<RecordBatch>>, Option<Vec<String>>), QueryError> {
) -> Result<
(
Option<Vec<RecordBatch>>,
Option<Vec<String>>,
Arc<QueryAdmissionGuard>,
),
QueryError,
> {
let mut session_state = QUERY_SESSION.get_ctx().state();
let time_range =
TimeRange::parse_human_time(&query_request.start_time, &query_request.end_time)?;
Expand All @@ -142,7 +159,7 @@ pub async fn get_records_and_fields_for_authorized_query(
.default_schema = tenant_id.as_deref().unwrap_or("public").to_owned();

let query: LogicalQuery = into_query(query_request, &session_state, time_range).await?;
let (records, fields) = execute(query, false, tenant_id).await?;
let (records, fields, query_admission) = execute(query, false, tenant_id).await?;

let records = match records {
Either::Left(vec_rb) => vec_rb,
Expand All @@ -151,7 +168,7 @@ pub async fn get_records_and_fields_for_authorized_query(
}
};

Ok((Some(records), Some(fields)))
Ok((Some(records), Some(fields), query_admission))
}

pub async fn query(req: HttpRequest, query_request: Query) -> Result<HttpResponse, QueryError> {
Expand Down Expand Up @@ -285,7 +302,8 @@ async fn handle_non_streaming_query(
tenant_id: &Option<String>,
) -> Result<HttpResponse, QueryError> {
let first_table_name = table_name[0].clone();
let (records, fields) = execute(query, query_request.streaming, tenant_id).await?;
let (records, fields, _query_admission) =
execute(query, query_request.streaming, tenant_id).await?;
let records = match records {
Either::Left(rbs) => rbs,
Either::Right(_) => {
Expand Down Expand Up @@ -338,7 +356,8 @@ async fn handle_streaming_query(
tenant_id: &Option<String>,
) -> Result<HttpResponse, QueryError> {
let first_table_name = table_name[0].clone();
let (records_stream, fields) = execute(query, query_request.streaming, tenant_id).await?;
let (records_stream, fields, query_admission) =
execute(query, query_request.streaming, tenant_id).await?;
let records_stream = match records_stream {
Either::Left(_) => {
return Err(QueryError::MalformedQuery(
Expand Down Expand Up @@ -385,12 +404,30 @@ async fn handle_streaming_query(
Box::pin(stream) as Pin<Box<dyn Stream<Item = Result<Bytes, actix_web::Error>>>>
};

let stream = AdmissionGuardedHttpStream {
inner: stream,
_query_admission: query_admission,
};

Ok(HttpResponse::Ok()
.content_type("application/x-ndjson")
.insert_header((TIME_ELAPSED_HEADER, total_time.as_str()))
.streaming(stream))
}

struct AdmissionGuardedHttpStream<S> {
inner: S,
_query_admission: Arc<QueryAdmissionGuard>,
}

impl<S: Stream + Unpin> Stream for AdmissionGuardedHttpStream<S> {
type Item = S::Item;

fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
Pin::new(&mut self.inner).poll_next(cx)
}
}

fn create_batch_processor()
-> impl FnMut(Result<RecordBatch, QueryError>) -> Result<Bytes, actix_web::Error> {
move |batch_result| match batch_result {
Expand Down Expand Up @@ -544,7 +581,8 @@ pub async fn get_counts(

let creds = extract_session_key_from_req(&req)?;

let (records, _) = get_records_and_fields(&query_request, &creds, &tenant_id).await?;
let (records, _, _query_admission) =
get_records_and_fields(&query_request, &creds, &tenant_id).await?;

if let Some(records) = records {
let json_records = record_batches_to_json(&records)?;
Expand Down
4 changes: 2 additions & 2 deletions src/handlers/http/query_context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -946,7 +946,7 @@ async fn execute_log_context_anchor_count(
filter_tags: None,
};

let (records, _) =
let (records, _, _query_admission) =
get_records_and_fields_for_authorized_query(&query_request, authorized_datasets, tenant_id)
.await?;
let records = records.unwrap_or_default();
Expand Down Expand Up @@ -992,7 +992,7 @@ async fn execute_log_context_rows(
filter_tags: None,
};

let (records, _) =
let (records, _, _query_admission) =
get_records_and_fields_for_authorized_query(&query_request, authorized_datasets, tenant_id)
.await?;
let records = records.unwrap_or_default();
Expand Down
Loading
Loading