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
47 changes: 1 addition & 46 deletions src/handlers/airplane.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,9 @@
*
*/

use arrow_array::RecordBatch;
use arrow_flight::PollInfo;
use arrow_flight::flight_service_server::FlightServiceServer;
use arrow_schema::ArrowError;
use serde_json::json;
use std::net::SocketAddr;
use std::time::Instant;
use tonic::codec::CompressionEncoding;
Expand All @@ -31,18 +29,12 @@ use futures_util::{Future, TryFutureExt};
use tonic::transport::{Identity, Server, ServerTlsConfig};
use tonic_web::GrpcWebLayer;

use crate::handlers::http::cluster::get_node_info;
use crate::handlers::http::modal::{NodeMetadata, NodeType};
use crate::handlers::http::query::into_query;
use crate::handlers::livetail::cross_origin_config;
use crate::metrics::QUERY_EXECUTE_TIME;
use crate::option::Mode;
use crate::parseable::{DEFAULT_TENANT, PARSEABLE};
use crate::query::{QUERY_SESSION, execute, resolve_stream_names};
use crate::utils::arrow::flight::{
append_temporary_events, get_query_from_ticket, into_flight_data, run_do_get_rpc,
send_to_ingester,
};
use crate::utils::arrow::flight::{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 Down Expand Up @@ -178,38 +170,6 @@ impl FlightService for AirServiceImpl {
.await
.map_err(|_| Status::internal("Failed to parse query"))?;

let event = if PARSEABLE.options.mode != Mode::All
&& send_to_ingester(
query.time_range.start.timestamp_millis(),
query.time_range.end.timestamp_millis(),
) {
let sql = format!("select * from \"{}\"", stream_name);
let start_time = ticket.start_time.clone();
let end_time = ticket.end_time.clone();
let out_ticket = json!({
"query": sql,
"startTime": start_time,
"endTime": end_time
})
.to_string();

let ingester_metadatas: Vec<NodeMetadata> = get_node_info(NodeType::Ingestor, &None)
.await
.map_err(|err| Status::failed_precondition(err.to_string()))?;
let mut minute_result: Vec<RecordBatch> = vec![];

for im in ingester_metadatas {
if let Ok(mut batches) = run_do_get_rpc(im, out_ticket.clone()).await {
minute_result.append(&mut batches);
}
}
let mr = minute_result.iter().collect::<Vec<_>>();
let event = append_temporary_events(&stream_name, mr).await?;
Some(event)
} else {
None
};

// try authorize
match Users.authorize(key.clone(), rbac::role::Action::Query, None, None) {
rbac::Response::Authorized => (),
Expand Down Expand Up @@ -260,11 +220,6 @@ impl FlightService for AirServiceImpl {
// Taxi out airplane
let out = into_flight_data(records);

if event.is_some() {
// Clear staging of stream once airplane has taxied
let _ = PARSEABLE.get_or_create_stream(&stream_name, &None).clear();
}

let time = time.elapsed().as_secs_f64();
let tenant_id = get_tenant_id_from_key(&key);
QUERY_EXECUTE_TIME
Expand Down
151 changes: 3 additions & 148 deletions src/parseable/staging/writer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,10 @@
*/

use std::{
collections::{HashMap, HashSet},
collections::HashMap,
fs::{self, File, OpenOptions},
io::BufWriter,
path::PathBuf,
sync::Arc,
};

use arrow_array::RecordBatch;
Expand All @@ -31,32 +30,19 @@ use arrow_ipc::{
writer::{IpcWriteOptions, StreamWriter},
};
use arrow_schema::Schema;
use arrow_select::concat::concat_batches;
use chrono::Utc;
use itertools::Itertools;
use once_cell::sync::Lazy;
use rand::distributions::{Alphanumeric, DistString};
use tracing::error;
use ulid::Ulid;

use crate::{
parseable::{ARROW_FILE_EXTENSION, PART_FILE_EXTENSION},
utils::{arrow::adapt_batch, time::TimeRange},
utils::time::TimeRange,
};

use super::StagingError;

const ENABLE_MEMORY_STAGING_VAR: &str = "ENABLE_MEMORY_STAGING";
pub static ENABLE_MEMORY_STAGING: Lazy<bool> = Lazy::new(|| {
if let Ok(var) = std::env::var(ENABLE_MEMORY_STAGING_VAR)
&& let Ok(var) = var.parse::<bool>()
{
var
} else {
true
}
});

const ONE_PARQUET_PER_ARROW_VAR: &str = "ONE_PARQUET_PER_ARROW";
static ONE_PARQUET_PER_ARROW: Lazy<bool> = Lazy::new(|| {
if let Ok(var) = std::env::var(ONE_PARQUET_PER_ARROW_VAR)
Expand All @@ -68,36 +54,11 @@ static ONE_PARQUET_PER_ARROW: Lazy<bool> = Lazy::new(|| {
}
});

// #[derive(Default)]
#[derive(Default)]
pub struct Writer {
pub mem: Option<MemWriter<4096>>,
pub disk: HashMap<String, DiskWriter>,
}

impl Writer {
/// Disk-only writer, for nodes that never serve queries from staging.
pub fn without_memory() -> Self {
Self {
mem: None,
disk: HashMap::new(),
}
}
}

impl Default for Writer {
fn default() -> Self {
let mem = if *ENABLE_MEMORY_STAGING {
Some(MemWriter::default())
} else {
None
};
Self {
mem,
disk: HashMap::default(),
}
}
}

impl Writer {
/// Appends a batch to the writer for its schema/minute file.
#[cfg_attr(feature = "hotpath", hotpath::measure)]
Expand Down Expand Up @@ -221,112 +182,6 @@ impl Drop for DiskWriter {
}
}

/// Structure to keep recordbatches in memory.
///
/// Any new schema is updated in the schema map.
/// Recordbatches are pushed to mutable buffer first and then concated together and pushed to read buffer
#[derive(Debug)]
pub struct MemWriter<const N: usize> {
schema: Schema,
// for checking uniqueness of schema
schema_map: HashSet<String>,
pub read_buffer: Vec<RecordBatch>,
pub mutable_buffer: MutableBuffer<N>,
}

impl<const N: usize> Default for MemWriter<N> {
fn default() -> Self {
Self {
schema: Schema::empty(),
schema_map: HashSet::default(),
read_buffer: Vec::default(),
mutable_buffer: MutableBuffer::default(),
}
}
}

impl<const N: usize> MemWriter<N> {
pub fn push(&mut self, schema_key: &str, rb: &RecordBatch) -> Result<(), StagingError> {
if !self.schema_map.contains(schema_key) {
self.schema_map.insert(schema_key.to_owned());
self.schema = Schema::try_merge([self.schema.clone(), (*rb.schema()).clone()])?;
}

if let Some(record) = self.mutable_buffer.push(rb) {
let record = concat_records(&Arc::new(self.schema.clone()), &record)?;
self.read_buffer.push(record);
}
Ok(())
}

pub fn clear(&mut self) {
self.schema = Schema::empty();
self.schema_map.clear();
self.read_buffer.clear();
self.mutable_buffer.inner.clear();
}

pub fn recordbatch_cloned(
&self,
schema: &Arc<Schema>,
) -> Result<Vec<RecordBatch>, StagingError> {
let mut read_buffer = self.read_buffer.clone();
if !self.mutable_buffer.inner.is_empty() {
let rb = concat_records(schema, &self.mutable_buffer.inner)?;
read_buffer.push(rb)
}

Ok(read_buffer
.into_iter()
.map(|rb| adapt_batch(schema.clone(), &rb))
.collect())
}
}

fn concat_records(
schema: &Arc<Schema>,
record: &[RecordBatch],
) -> Result<RecordBatch, StagingError> {
let records = record
.iter()
.map(|x| adapt_batch(schema.clone(), x))
.collect_vec();
Ok(concat_batches(schema, records.iter())?)
}

#[derive(Debug, Default)]
pub struct MutableBuffer<const N: usize> {
pub inner: Vec<RecordBatch>,
}

impl<const N: usize> MutableBuffer<N> {
fn push(&mut self, rb: &RecordBatch) -> Option<Vec<RecordBatch>> {
if self.inner.len() + rb.num_rows() >= N {
let left = N - self.inner.len();
let right = rb.num_rows() - left;
let left_slice = rb.slice(0, left);
let right_slice = if left < rb.num_rows() {
Some(rb.slice(left, right))
} else {
None
};
self.inner.push(left_slice);
// take all records
let src = Vec::with_capacity(self.inner.len());
let inner = std::mem::replace(&mut self.inner, src);

if let Some(right_slice) = right_slice {
self.inner.push(right_slice);
}

Some(inner)
} else {
self.inner.push(rb.clone());
None
}
}
}

#[cfg(test)]
mod tests {
use std::{fs::File, sync::Arc};
Expand Down
76 changes: 26 additions & 50 deletions src/parseable/streams.rs
Original file line number Diff line number Diff line change
Expand Up @@ -790,13 +790,7 @@ impl Stream {
metadata.schema.insert(field.name().clone(), field);
}
}
// The in-memory staging buffer only serves queries, which ingestors never run, and
// it cannot merge batches across a resolved type change.
let writer = if resolving {
Writer::without_memory()
} else {
Writer::default()
};
let writer = Writer::default();

Arc::new(Self {
stream_name: stream_name.clone(),
Expand Down Expand Up @@ -1011,9 +1005,6 @@ impl Stream {
disk.range.clone(),
)?;
}
if let Some(mem) = writer.mem.as_mut() {
mem.push(&group[0].schema_key, &record)?;
}
Ok(())
})
.map_err(|err| err.to_string());
Expand Down Expand Up @@ -1079,6 +1070,31 @@ impl Stream {
.collect()
}

pub fn all_arrow_files(&self) -> Vec<PathBuf> {
let Ok(dir) = self.data_path.read_dir() else {
return vec![];
};

dir.flatten()
.map(|file| file.path())
.filter(|file| {
// `extension()` of `x.arrows.part` is `part`, so match on the name.
file.file_name()
.and_then(|name| name.to_str())
.is_some_and(|name| {
name.ends_with(&format!(".{ARROW_FILE_EXTENSION}"))
|| name.ends_with(ARROW_PART_FILE_SUFFIX)
})
})
.filter_map(|f| {
let modified = f.metadata().ok().and_then(|m| m.modified().ok());
modified.map(|modified_time| (f, modified_time))
})
.sorted_by_key(|(_, modified_time)| *modified_time)
.map(|(f, _)| f)
.collect()
}

pub fn inprocess_arrow_files(&self) -> Vec<PathBuf> {
let Ok(dir) = self.data_path.read_dir() else {
return vec![];
Expand Down Expand Up @@ -1586,42 +1602,6 @@ impl Stream {
Ok(())
}

pub fn recordbatches_cloned(
&self,
schema: &Arc<Schema>,
) -> Result<Vec<RecordBatch>, StagingError> {
let mut writer = self.writer.lock().map_err(|poisoned| {
StagingError::PoisonError(PoisonError::new(format!(
"Writer lock poisoned while cloning record batches for stream {} - {}",
self.stream_name, poisoned
)))
})?;

if let Some(mem) = writer.mem.as_mut() {
mem.recordbatch_cloned(schema)
} else {
Ok(Vec::new())
}
}

pub fn clear(&self) -> Result<(), StagingError> {
if let Some(m) = self
.writer
.lock()
.map_err(|poisoned| {
StagingError::PoisonError(PoisonError::new(format!(
"Writer lock poisoned while clearing stream {} - {}",
self.stream_name, poisoned
)))
})?
.mem
.as_mut()
{
m.clear()
}
Ok(())
}

#[cfg_attr(feature = "hotpath", hotpath::measure)]
pub fn flush(&self, forced: bool) -> Result<(), StagingError> {
let _span = info_span!("flush", stream_name = %self.stream_name, forced).entered();
Expand Down Expand Up @@ -1649,10 +1629,6 @@ impl Stream {
)))
})?;

if let Some(mem) = writer.mem.as_mut() {
mem.clear();
}

// Finalize and rename files while holding the writer lock so staging
// deletion cannot remove them before DiskWriter::drop completes.
drop(writer.take_flushable_disk(forced));
Expand Down
Loading
Loading