use std::net::SocketAddrV4;
use std::os::unix::fs::DirBuilderExt;
use std::os::unix::process::ExitStatusExt;
use std::path::{Path, PathBuf};
use std::process::{ExitStatus, Stdio};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use crate::proto as pb;
use crate::proto::Message;
use bytes::Bytes;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::process::{Child, ChildStderr, ChildStdin, ChildStdout, Command};
use tokio::task::JoinHandle;
use crate::catalog::TableKind;
use crate::observe::{Ended, Failure, Kind, Observer, Report, Work};
use crate::pool::Pool;
use crate::writer::{Budget, CommittedPart, Housekept, Insert, Inserted, MergeCandidate, Merged, Outcome, PlannedMerge, Remaining, TableName, Writer};
use crate::{Error, PartInfo, Tenant, TenantKey};
const LOG_KEPT: usize = 16 << 10;
const NO_AMBIENT_CREDENTIALS: [(&str, &str); 3] =
[("AWS_SHARED_CREDENTIALS_FILE", "/dev/null"), ("AWS_CONFIG_FILE", "/dev/null"), ("AWS_EC2_METADATA_DISABLED", "true")];
pub const DEFAULT_DEADLINE: Duration = Duration::from_secs(600);
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WorkerCommand {
pub program: PathBuf,
pub args: Vec<String>,
pub envs: Vec<(String, String)>,
pub scratch: PathBuf,
pub sandbox: Option<Sandbox>,
pub forking: bool,
}
impl WorkerCommand {
pub fn clickhouse(binary: impl Into<PathBuf>) -> WorkerCommand {
WorkerCommand::new(binary).arg("libch-worker")
}
pub fn new(program: impl Into<PathBuf>) -> WorkerCommand {
WorkerCommand {
program: program.into(),
args: Vec::new(),
envs: Vec::new(),
scratch: std::env::temp_dir().join("libch-workers"),
sandbox: None,
forking: false,
}
}
pub fn arg(mut self, arg: impl Into<String>) -> WorkerCommand {
self.args.push(arg.into());
self
}
pub fn env(mut self, name: impl Into<String>, value: impl Into<String>) -> WorkerCommand {
self.envs.push((name.into(), value.into()));
self
}
pub fn scratch(mut self, directory: impl Into<PathBuf>) -> WorkerCommand {
self.scratch = directory.into();
self
}
pub fn sandboxed(mut self, sandbox: Sandbox) -> WorkerCommand {
self.sandbox = Some(sandbox);
self
}
pub fn forking(mut self) -> WorkerCommand {
self.forking = true;
self
}
fn arguments(&self, scratch: &Path) -> Vec<String> {
let mut arguments = self.args.clone();
arguments.push(format!("--path={}", scratch.display()));
if self.forking {
arguments.push("--fork".into());
}
if let Some(sandbox) = &self.sandbox {
arguments.push("--sandbox".into());
if !sandbox.connect_ports.is_empty() {
let ports: Vec<String> = sandbox.connect_ports.iter().map(u16::to_string).collect();
arguments.push(format!("--allow-connect={}", ports.join(",")));
}
arguments.extend(sandbox.read_paths.iter().map(|path| format!("--allow-read={}", path.display())));
}
arguments
}
pub async fn probe(&self, probes: &[Probe]) -> Result<Vec<Probed>, Error> {
let scratch = Scratch::make(&self.scratch)?;
let mut command = Command::new(&self.program);
let own = WorkerCommand { forking: false, ..self.clone() };
command.args(own.arguments(scratch.path())).args(probes.iter().map(Probe::argument)).env_clear().envs(NO_AMBIENT_CREDENTIALS);
command.envs(self.envs.iter().map(|(name, value)| (name.as_str(), value.as_str()))).stdin(Stdio::null()).kill_on_drop(true);
let program = self.program.display();
let output = command.output().await.map_err(|error| Error::Worker { message: format!("{program} did not start: {error}") })?;
let failed =
|| Error::Worker { message: format!("{program} failed its probes with {}: {}", output.status, String::from_utf8_lossy(&output.stderr).trim()) };
if !output.status.success() {
return Err(failed());
}
let answers = String::from_utf8_lossy(&output.stdout);
let errors: Vec<Option<i32>> =
answers.lines().map(|line| line.rsplit_once(": ").and_then(|(_, outcome)| probe_outcome(outcome))).collect::<Option<_>>().ok_or_else(failed)?;
if errors.len() != probes.len() {
return Err(failed());
}
Ok(probes.iter().cloned().zip(errors).map(|(probe, error)| Probed { probe, error }).collect())
}
}
fn probe_outcome(outcome: &str) -> Option<Option<i32>> {
if outcome == "ok" {
return Some(None);
}
outcome.split(' ').next().and_then(|number| number.parse().ok()).map(Some)
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Sandbox {
pub connect_ports: Vec<u16>,
pub read_paths: Vec<PathBuf>,
}
impl Sandbox {
pub fn reaching(store: &str, s3_endpoint: &str) -> Result<Sandbox, Error> {
let store_port = store.rsplit_once(':').and_then(|(_, port)| port.parse().ok());
let store_port = store_port.ok_or_else(|| Error::Other(format!("the store `{store}` names no port")))?;
let endpoint = url::Url::parse(s3_endpoint).map_err(|error| Error::S3(format!("endpoint `{s3_endpoint}`: {error}")))?;
let s3_port = endpoint.port_or_known_default().ok_or_else(|| Error::S3(format!("endpoint `{s3_endpoint}` names no port")))?;
let mut connect_ports = vec![store_port, s3_port];
connect_ports.dedup();
Ok(Sandbox { connect_ports, read_paths: Vec::new() })
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Probe {
Read(PathBuf),
Write(PathBuf),
Execute(PathBuf),
Connect(SocketAddrV4),
UnixSocket,
Signal(u32),
Trace(u32),
}
impl Probe {
fn argument(&self) -> String {
match self {
Probe::Read(path) => format!("--probe-read={}", path.display()),
Probe::Write(path) => format!("--probe-write={}", path.display()),
Probe::Execute(path) => format!("--probe-execute={}", path.display()),
Probe::Connect(address) => format!("--probe-connect={address}"),
Probe::UnixSocket => "--probe-unix=stream".into(),
Probe::Signal(pid) => format!("--probe-signal={pid}"),
Probe::Trace(pid) => format!("--probe-trace={pid}"),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Probed {
pub probe: Probe,
pub error: Option<i32>,
}
#[derive(Debug)]
struct Scratch(PathBuf);
impl Scratch {
fn make(base: &Path) -> Result<Scratch, Error> {
let directory = base.join(format!("worker-{:016x}", rand::random::<u64>()));
let made = std::fs::create_dir_all(base).and_then(|()| std::fs::DirBuilder::new().mode(0o700).create(&directory));
made.map_err(|error| Error::Worker { message: format!("a worker's directory {} could not be made: {error}", directory.display()) })?;
Ok(Scratch(directory))
}
fn path(&self) -> &Path {
&self.0
}
}
impl Drop for Scratch {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Described {
pub tables: Vec<DescribedTable>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DescribedTable {
pub name: TableName,
pub uuid: String,
pub kind: TableKind,
pub engine: Option<String>,
pub views: Vec<ViewEdge>,
pub parts: Vec<DescribedPart>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ViewEdge {
pub view: TableName,
pub target: TableName,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DescribedPart {
pub name: String,
pub partition_id: String,
pub min_block: i64,
pub max_block: i64,
pub level: u32,
pub mutation: i64,
pub active: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Shared {
pub owner_version: u64,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Usage {
pub operations: u64,
pub inodedb_commits: u64,
pub inodedb_stats: u64,
pub inodedb_reads: u64,
pub inodedb_lists: u64,
pub s3_reads: u64,
pub s3_writes: u64,
pub cpu: Duration,
pub peak_anonymous_memory_bytes: u64,
pub peak_threads: u32,
pub inodedb_time: Duration,
pub inodedb_retries: u64,
pub s3_read_time: Duration,
pub s3_write_time: Duration,
pub s3_throttled: u64,
pub s3_bytes_read: u64,
pub s3_bytes_written: u64,
}
impl std::ops::AddAssign for Usage {
fn add_assign(&mut self, more: Usage) {
self.operations += more.operations;
self.inodedb_commits += more.inodedb_commits;
self.inodedb_stats += more.inodedb_stats;
self.inodedb_reads += more.inodedb_reads;
self.inodedb_lists += more.inodedb_lists;
self.s3_reads += more.s3_reads;
self.s3_writes += more.s3_writes;
self.cpu += more.cpu;
self.peak_anonymous_memory_bytes = self.peak_anonymous_memory_bytes.max(more.peak_anonymous_memory_bytes);
self.peak_threads = self.peak_threads.max(more.peak_threads);
self.inodedb_time += more.inodedb_time;
self.inodedb_retries += more.inodedb_retries;
self.s3_read_time += more.s3_read_time;
self.s3_write_time += more.s3_write_time;
self.s3_throttled += more.s3_throttled;
self.s3_bytes_read += more.s3_bytes_read;
self.s3_bytes_written += more.s3_bytes_written;
}
}
impl Usage {
pub fn inodedb_calls(&self) -> u64 {
self.inodedb_commits + self.inodedb_stats + self.inodedb_reads + self.inodedb_lists
}
pub(crate) fn of(worker: &pb::Usage) -> Usage {
Usage {
operations: 1,
inodedb_commits: u64::from(worker.inodedb_commits),
inodedb_stats: u64::from(worker.inodedb_stats),
inodedb_reads: u64::from(worker.inodedb_reads),
inodedb_lists: u64::from(worker.inodedb_lists),
s3_reads: u64::from(worker.s3_reads),
s3_writes: u64::from(worker.s3_writes),
cpu: Duration::from_micros(worker.cpu_microseconds),
peak_anonymous_memory_bytes: worker.anonymous_memory_bytes,
peak_threads: worker.threads,
inodedb_time: Duration::from_micros(worker.inodedb_microseconds),
inodedb_retries: u64::from(worker.inodedb_retries),
s3_read_time: Duration::from_micros(worker.s3_read_microseconds),
s3_write_time: Duration::from_micros(worker.s3_write_microseconds),
s3_throttled: u64::from(worker.s3_throttled),
s3_bytes_read: worker.s3_bytes_read,
s3_bytes_written: worker.s3_bytes_written,
}
}
}
#[derive(Clone, Debug)]
enum Workers {
Started(WorkerCommand),
Pooled(Pool),
}
#[derive(Clone, Debug)]
pub struct OpWriter {
workers: Workers,
tenant: Tenant,
key: TenantKey,
settings_xml: String,
memory_limit: Option<u64>,
deadline: Duration,
at_least_once: bool,
usage: Arc<Mutex<Usage>>,
observer: Observing,
}
#[derive(Clone, Default)]
pub(crate) struct Observing(pub(crate) Option<Arc<dyn Observer>>);
impl std::fmt::Debug for Observing {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(if self.0.is_some() { "Some(Observer)" } else { "None" })
}
}
#[derive(Debug)]
pub(crate) struct Failed {
pub(crate) failure: Failure,
pub(crate) error: Error,
}
impl Failed {
pub(crate) fn new(failure: Failure, error: Error) -> Failed {
Failed { failure, error }
}
}
pub(crate) struct Run {
pub(crate) response: Result<pb::Response, Failed>,
pub(crate) queued: Duration,
pub(crate) waiting_worker: bool,
}
impl OpWriter {
pub fn new(command: WorkerCommand, tenant: &Tenant, key: impl Into<TenantKey>) -> OpWriter {
OpWriter::over(Workers::Started(command), tenant, key.into())
}
pub(crate) fn pooled(pool: Pool, tenant: &Tenant, key: TenantKey) -> OpWriter {
let observer = pool.observer();
OpWriter { observer, ..OpWriter::over(Workers::Pooled(pool), tenant, key) }
}
fn over(workers: Workers, tenant: &Tenant, key: TenantKey) -> OpWriter {
OpWriter {
workers,
tenant: tenant.clone(),
key,
settings_xml: String::new(),
memory_limit: None,
deadline: DEFAULT_DEADLINE,
at_least_once: false,
usage: Arc::default(),
observer: Observing::default(),
}
}
pub fn observed(mut self, observer: Arc<dyn Observer>) -> OpWriter {
self.observer = Observing(Some(observer));
self
}
pub fn with_settings_xml(mut self, settings_xml: impl Into<String>) -> OpWriter {
self.settings_xml = settings_xml.into();
self
}
fn settings_document(&self) -> String {
match self.memory_limit {
Some(bytes) => format!("{}<max_server_memory_usage>{bytes}</max_server_memory_usage>", self.settings_xml),
None => self.settings_xml.clone(),
}
}
pub fn with_memory_limit(mut self, bytes: u64) -> OpWriter {
self.memory_limit = Some(bytes);
self
}
pub fn with_deadline(mut self, deadline: Duration) -> OpWriter {
self.deadline = deadline;
self
}
pub fn at_least_once(mut self) -> OpWriter {
self.at_least_once = true;
self
}
pub fn usage(&self) -> Usage {
*self.usage.lock().expect("no panics holding the usage")
}
pub async fn describe(&self, parts: bool) -> Result<Described, Error> {
let read = |response| {
let outcome = outcome(response, |result| match result {
pb::response::Result::Described(described) => Some(described),
_ => None,
})?;
match outcome {
Outcome::Committed(described) => described.tables.into_iter().map(described_table).collect::<Result<_, _>>().map(|tables| Described { tables }),
other => Err(protocol(format!("answered a describe with `{}`", other.name()))),
}
};
self.operate(Kind::Describe, None, pb::request::Operation::Describe(pb::Describe { parts }), None, read, |_, _| Ended::Committed).await
}
pub async fn share(&self) -> Result<Shared, Error> {
let read = |response| {
let outcome = outcome(response, |result| match result {
pb::response::Result::Shared(shared) => Some(shared),
_ => None,
})?;
match outcome {
Outcome::Committed(shared) => Ok(Shared { owner_version: shared.owner_version }),
other => Err(protocol(format!("answered a share with `{}`", other.name()))),
}
};
self.operate(Kind::Share, None, pb::request::Operation::Share(pb::Share {}), None, read, |_, _| Ended::Committed).await
}
async fn operate<T>(
&self,
kind: Kind,
table: Option<&TableName>,
operation: pb::request::Operation,
data: Option<&Bytes>,
read: impl FnOnce(pb::Response) -> Result<T, Error>,
account: impl FnOnce(&T, &mut Work) -> Ended,
) -> Result<T, Error> {
let batch_bytes = data.map_or(0, |data| data.len() as u64);
let mut pending = Pending { writer: self, kind, table, began: Instant::now(), batch_bytes, reported: false };
let run = self.call(operation, data).await;
let mut work = Work { batch_bytes, ..Work::default() };
let mut usage = None;
let (result, ended) = match run.response {
Err(failed) => (Err(failed.error), Ended::Failed(failed.failure)),
Ok(response) => {
if let Some(counted) = &response.usage {
let counted = Usage::of(counted);
*self.usage.lock().expect("no panics holding the usage") += counted;
usage = Some(counted);
}
let failure = if response.status == pb::Status::Failed as i32 {
Failure::Exception { code: (response.exception_code != 0).then_some(response.exception_code) }
} else {
Failure::Protocol
};
match read(response) {
Ok(value) => {
let ended = account(&value, &mut work);
(Ok(value), ended)
}
Err(error) => (Err(error), Ended::Failed(failure)),
}
}
};
pending.reported = true;
if let Some(observer) = &self.observer.0 {
let (queued, waiting_worker) = (run.queued, run.waiting_worker);
observer.operation(&Report { queued, waiting_worker, usage, work, ..self.ending(kind, table, ended, pending.began) });
}
result
}
fn ending(&self, kind: Kind, table: Option<&TableName>, ended: Ended, began: Instant) -> Report {
Report {
kind,
store: self.tenant.store.clone(),
tenant: self.tenant.root.clone(),
table: table.cloned(),
ended,
elapsed: began.elapsed(),
queued: Duration::ZERO,
waiting_worker: false,
usage: None,
work: Work::default(),
}
}
async fn call(&self, operation: pb::request::Operation, data: Option<&Bytes>) -> Run {
let request = pb::Request {
tenant: Some(pb::Tenant {
inodedb_endpoint: self.tenant.store.clone(),
inodedb_key: self.key.to_string(),
s3: Some(pb::S3 {
endpoint: self.tenant.s3.endpoint.clone(),
bucket: self.tenant.s3.bucket.clone(),
prefix: self.tenant.s3.prefix.clone(),
region: self.tenant.s3.region.clone(),
access_key: self.tenant.s3.access_key.clone(),
secret_key: self.tenant.s3.secret_key.clone(),
}),
}),
settings_xml: self.settings_document(),
operation: Some(operation),
};
match &self.workers {
Workers::Started(command) => {
let response = match Worker::start(command) {
Err(error) => Err(Failed::new(Failure::Start, error)),
Ok(mut worker) if command.forking => worker.serve(&request, data, self.deadline).await.0,
Ok(worker) => worker.run(&request, data, self.deadline).await,
};
Run { response, queued: Duration::ZERO, waiting_worker: false }
}
Workers::Pooled(pool) => pool.run(&request, data, self.deadline).await,
}
}
}
struct Pending<'a> {
writer: &'a OpWriter,
kind: Kind,
table: Option<&'a TableName>,
began: Instant,
batch_bytes: u64,
reported: bool,
}
impl Drop for Pending<'_> {
fn drop(&mut self) {
if let (false, Some(observer)) = (self.reported, &self.writer.observer.0) {
let work = Work { batch_bytes: self.batch_bytes, ..Work::default() };
observer.operation(&Report { work, ..self.writer.ending(self.kind, self.table, Ended::Failed(Failure::Cancelled), self.began) });
}
}
}
pub(crate) struct Worker {
program: String,
child: Child,
stdin: ChildStdin,
stdout: ChildStdout,
log: Arc<Log>,
logging: JoinHandle<()>,
scratch: Scratch,
}
impl Worker {
pub(crate) fn start(command: &WorkerCommand) -> Result<Worker, Error> {
let program = command.program.display().to_string();
let scratch = Scratch::make(&command.scratch)?;
let mut child = Command::new(&command.program)
.args(command.arguments(scratch.path()))
.env_clear()
.envs(NO_AMBIENT_CREDENTIALS)
.envs(command.envs.iter().map(|(name, value)| (name.as_str(), value.as_str())))
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true)
.spawn()
.map_err(|error| Error::Worker { message: format!("{program} did not start: {error}") })?;
let stdin = child.stdin.take().expect("stdin is piped");
let stdout = child.stdout.take().expect("stdout is piped");
let log = Arc::new(Log::default());
let logging = tokio::spawn(keep_log(child.stderr.take().expect("stderr is piped"), log.clone()));
Ok(Worker { program, child, stdin, stdout, log, logging, scratch })
}
pub(crate) fn has_exited(&mut self) -> bool {
!matches!(self.child.try_wait(), Ok(None))
}
pub(crate) async fn kill(mut self) {
let _ = self.child.kill().await;
}
pub(crate) async fn run(self, request: &pb::Request, data: Option<&Bytes>, deadline: Duration) -> Result<pb::Response, Failed> {
let Worker { scratch: _scratch, program, mut child, mut stdin, stdout, log, logging } = self;
let mut stdout = stdout.take((pb::FRAME_HEADER + pb::MAX_FRAME + 1) as u64);
let send = async move {
send_request(&mut stdin, request, data).await?;
stdin.shutdown().await
};
let receive = async {
let mut answer = Vec::new();
stdout.read_to_end(&mut answer).await.map(|_| answer)
};
let exchange = async {
let (sent, answer) = tokio::join!(send, receive);
let status = child.wait().await;
let _ = logging.await;
(sent, answer, status)
};
let Ok((sent, answer, status)) = tokio::time::timeout(deadline, exchange).await else {
return Err(past_deadline(&program, deadline));
};
let log = String::from_utf8_lossy(&log.take()).into_owned();
let exited = |message: String| Failed::new(Failure::Exited, Error::Worker { message });
let status = status.map_err(|error| exited(format!("{program} could not be waited for: {error}")))?;
let answer = answer.map_err(|error| exited(format!("{program}'s answer could not be read: {error}")))?;
decode(status, &answer).map_err(|(failure, problem)| {
let unsent = sent.err().map(|error| format!("; the request did not all go out: {error}")).unwrap_or_default();
Failed::new(failure, Error::Worker { message: format!("{program} {problem}{unsent}{}", log_tail(&log)) })
})
}
pub(crate) async fn serve(&mut self, request: &pb::Request, data: Option<&Bytes>, deadline: Duration) -> (Result<pb::Response, Failed>, bool) {
let program = self.program.clone();
self.log.take();
let (stdin, stdout) = (&mut self.stdin, &mut self.stdout);
let send = async move {
send_request(stdin, request, data).await?;
stdin.flush().await
};
let receive = async move {
let mut answer = Vec::new();
loop {
let mut header = [0u8; pb::FRAME_HEADER];
stdout.read_exact(&mut header).await?;
if header == pb::FORK_TRAILER {
let mut status = [0u8; 4];
stdout.read_exact(&mut status).await?;
return Ok::<_, std::io::Error>((answer, ExitStatus::from_raw(i32::from_le_bytes(status))));
}
let length = pb::frame_length(header)?;
let start = answer.len();
answer.extend_from_slice(&header);
answer.resize(start + pb::FRAME_HEADER + length, 0);
stdout.read_exact(&mut answer[start + pb::FRAME_HEADER..]).await?;
}
};
let exchange = async move {
tokio::pin!(send, receive);
let mut sent = None;
loop {
tokio::select! {
biased;
result = &mut send, if sent.is_none() => sent = Some(result),
received = &mut receive => return (sent, received),
}
}
};
let Ok((sent, received)) = tokio::time::timeout(deadline, exchange).await else {
return (Err(past_deadline(&program, deadline)), false);
};
let (answer, status) = match received {
Ok(received) => received,
Err(error) => {
let log = String::from_utf8_lossy(&self.log.take()).into_owned();
let message = format!("{program}'s answer could not be read: {error}{}", log_tail(&log));
return (Err(Failed::new(Failure::Exited, Error::Worker { message })), false);
}
};
let log = self.log.take_operation().await;
let unsent = match sent {
Some(Ok(())) => None,
Some(Err(error)) => Some(format!("; the request did not all go out: {error}")),
None => Some("; the child ended before the request had all gone out".to_string()),
};
let response = decode(status, &answer).map_err(|(failure, problem)| {
let message = format!("{program}'s child {problem}{}{}", unsent.as_deref().unwrap_or_default(), log_tail(&String::from_utf8_lossy(&log)));
Failed::new(failure, Error::Worker { message })
});
let reusable = response.is_ok() && unsent.is_none();
(response, reusable)
}
}
fn past_deadline(program: &str, deadline: Duration) -> Failed {
Failed::new(Failure::Deadline, Error::Worker { message: format!("{program} did not finish within {deadline:?} and was killed") })
}
async fn send_request(stdin: &mut ChildStdin, request: &pb::Request, data: Option<&Bytes>) -> std::io::Result<()> {
stdin.write_all(&pb::message_frame(request)).await?;
if let Some(data) = data {
for chunk in data.chunks(pb::DATA_FRAME) {
stdin.write_all(&(chunk.len() as u32).to_le_bytes()).await?;
stdin.write_all(chunk).await?;
}
stdin.write_all(&0u32.to_le_bytes()).await?;
}
Ok(())
}
#[derive(Default)]
struct Log {
kept: Mutex<Vec<u8>>,
grew: tokio::sync::Notify,
}
impl Log {
fn kept(&self) -> std::sync::MutexGuard<'_, Vec<u8>> {
self.kept.lock().expect("no panics holding the log")
}
fn take(&self) -> Vec<u8> {
std::mem::take(&mut *self.kept())
}
async fn take_operation(&self) -> Vec<u8> {
let marked = async {
loop {
let grew = self.grew.notified();
if self.kept().contains(&pb::FORK_LOG_END) {
return;
}
grew.await;
}
};
let _ = tokio::time::timeout(Duration::from_millis(200), marked).await;
let mut kept = self.kept();
match kept.iter().position(|&byte| byte == pb::FORK_LOG_END) {
Some(mark) => {
let rest = kept.split_off(mark + 1);
let mut operation = std::mem::replace(&mut *kept, rest);
operation.pop();
operation
}
None => std::mem::take(&mut *kept),
}
}
}
async fn keep_log(mut stderr: ChildStderr, log: Arc<Log>) {
let mut buffer = [0u8; 4096];
while let Ok(read) = stderr.read(&mut buffer).await {
if read == 0 {
break;
}
{
let mut kept = log.kept();
kept.extend_from_slice(&buffer[..read]);
if kept.len() > 2 * LOG_KEPT {
let excess = kept.len() - LOG_KEPT;
kept.drain(..excess);
}
}
log.grew.notify_waiters();
}
let mut kept = log.kept();
let excess = kept.len().saturating_sub(LOG_KEPT);
kept.drain(..excess);
}
fn decode(status: ExitStatus, answer: &[u8]) -> Result<pb::Response, (Failure, String)> {
if !status.success() {
return Err((Failure::Exited, format!("failed with {status}")));
}
if answer.len() < pb::FRAME_HEADER {
return Err((Failure::Exited, format!("exited without a response: it wrote {} bytes", answer.len())));
}
let broken = |problem: String| (Failure::Protocol, problem);
let header: [u8; pb::FRAME_HEADER] = answer[..pb::FRAME_HEADER].try_into().expect("the slice has the header's length");
let length = pb::frame_length(header).map_err(|error| broken(format!("wrote no response frame: {error}")))?;
if answer.len() != pb::FRAME_HEADER + length {
return Err(broken(format!("wrote {} bytes where one response frame of {} is expected", answer.len(), pb::FRAME_HEADER + length)));
}
pb::Response::decode(&answer[pb::FRAME_HEADER..]).map_err(|error| broken(format!("wrote a response that does not decode: {error}")))
}
fn log_tail(log: &str) -> String {
let log = log.trim();
if log.is_empty() {
return String::new();
}
let start = log.len().saturating_sub(2_000);
let start = (start..=log.len()).find(|&at| log.is_char_boundary(at)).unwrap_or(log.len());
format!("; its log ends: {}", &log[start..])
}
fn protocol(problem: String) -> Error {
Error::Worker { message: format!("the worker {problem}") }
}
fn outcome<T>(response: pb::Response, take: impl FnOnce(pb::response::Result) -> Option<T>) -> Result<Outcome<T>, Error> {
match pb::Status::try_from(response.status) {
Ok(pb::Status::Ok) => match response.result.and_then(take) {
Some(result) => Ok(Outcome::Committed(result)),
None => Err(protocol("answered OK without the operation's result".into())),
},
Ok(pb::Status::Duplicate) => Ok(Outcome::Duplicate),
Ok(pb::Status::SchemaChanged) => Ok(Outcome::SchemaChanged),
Ok(pb::Status::Fenced) => Ok(Outcome::Fenced),
Ok(pb::Status::ClaimLost) => Ok(Outcome::ClaimLost),
Ok(pb::Status::Refused) => Ok(Outcome::Refused(response.message)),
Ok(pb::Status::Failed) if response.exception_code != 0 => Err(Error::ClickHouse { code: response.exception_code, message: response.message }),
Ok(pb::Status::Failed) => Err(Error::Worker { message: format!("the operation failed: {}", response.message) }),
Ok(pb::Status::Unspecified) | Err(_) => Err(protocol(format!("answered with the unknown status {}", response.status))),
}
}
fn part(name: &str) -> Result<PartInfo, Error> {
PartInfo::parse(name).ok_or_else(|| protocol(format!("named `{name}`, which is no part name")))
}
fn table_name(name: Option<pb::TableName>) -> Result<TableName, Error> {
name.map(|name| TableName::new(name.database, name.table)).ok_or_else(|| protocol("left a table's name out of its answer".into()))
}
fn pb_table(name: &TableName) -> Option<pb::TableName> {
Some(pb::TableName { database: name.database.clone(), table: name.table.clone() })
}
fn described_table(table: pb::Table) -> Result<DescribedTable, Error> {
let kind = match pb::table::Kind::try_from(table.kind) {
Ok(pb::table::Kind::Table) => TableKind::Table,
Ok(pb::table::Kind::MaterializedView) => TableKind::MaterializedView,
Ok(pb::table::Kind::View) => TableKind::View,
Ok(pb::table::Kind::Dictionary) => TableKind::Dictionary,
Ok(pb::table::Kind::Unspecified) | Err(_) => TableKind::Other,
};
let views =
table.views.into_iter().map(|edge| Ok(ViewEdge { view: table_name(edge.view)?, target: table_name(edge.target)? })).collect::<Result<_, Error>>()?;
let parts = table
.parts
.into_iter()
.map(|part| DescribedPart {
name: part.name,
partition_id: part.partition_id,
min_block: part.min_block,
max_block: part.max_block,
level: part.level,
mutation: part.mutation,
active: part.active,
})
.collect();
Ok(DescribedTable { name: table_name(table.name)?, uuid: table.uuid, kind, engine: (!table.engine.is_empty()).then_some(table.engine), views, parts })
}
impl Writer for OpWriter {
async fn insert(&self, insert: Insert<'_>) -> Result<Outcome<Inserted>, Error> {
let operation =
pb::Insert { table: pb_table(insert.table), format: insert.format.to_string(), token: insert.token.to_string(), at_least_once: self.at_least_once };
let read = |response| {
let outcome = outcome(response, |result| match result {
pb::response::Result::Inserted(inserted) => Some(inserted),
_ => None,
})?;
let Outcome::Committed(inserted) = outcome else { return Ok(retype(outcome)) };
let counter_conflicts = u64::from(inserted.counter_conflicts);
let parts = inserted.parts.into_iter().map(|committed| {
Ok(CommittedPart { table: table_name(committed.table)?, part: part(&committed.part)?, rows: committed.rows, bytes: committed.bytes })
});
Ok(Outcome::Committed(Inserted { parts: Some(parts.collect::<Result<_, Error>>()?), counter_conflicts }))
};
let account = |outcome: &Outcome<Inserted>, work: &mut Work| {
if let Outcome::Committed(Inserted { parts: Some(parts), .. }) = outcome {
work.rows_inserted = parts.iter().filter(|committed| committed.table == *insert.table).map(|committed| committed.rows).sum();
work.parts_committed = parts.len() as u64;
work.part_rows = parts.iter().map(|committed| committed.rows).sum();
work.part_bytes = parts.iter().map(|committed| committed.bytes).sum();
}
ended(outcome)
};
self.operate(Kind::Insert, Some(insert.table), pb::request::Operation::Insert(operation), Some(&insert.data), read, account).await
}
async fn plan(&self, table: &TableName, budget: &Budget) -> Result<Vec<PlannedMerge>, Error> {
let operation = pb::Plan { table: pb_table(table), max_merges: u32::try_from(budget.max_merges).unwrap_or(u32::MAX) };
let read = |response| {
let outcome = outcome(response, |result| match result {
pb::response::Result::Planned(planned) => Some(planned),
_ => None,
})?;
let Outcome::Committed(planned) = outcome else { return Err(protocol(format!("answered a plan with `{}`", outcome.name()))) };
planned
.candidates
.into_iter()
.map(|candidate| {
let sources = candidate.sources.iter().map(|source| part(source)).collect::<Result<_, _>>()?;
Ok(PlannedMerge {
candidate: MergeCandidate { partition_id: candidate.partition_id, sources },
rows: candidate.rows,
bytes: candidate.bytes,
})
})
.collect()
};
let account = |planned: &Vec<PlannedMerge>, work: &mut Work| {
work.merges_planned = planned.len() as u64;
Ended::Committed
};
self.operate(Kind::Plan, Some(table), pb::request::Operation::Plan(operation), None, read, account).await
}
async fn merge(&self, table: &TableName, candidate: &MergeCandidate) -> Result<Outcome<Merged>, Error> {
let operation =
pb::Merge { table: pb_table(table), partition_id: candidate.partition_id.clone(), sources: candidate.sources.iter().map(PartInfo::name).collect() };
let read = |response| {
let outcome = outcome(response, |result| match result {
pb::response::Result::Merged(merged) => Some(merged),
_ => None,
})?;
let Outcome::Committed(merged) = outcome else { return Ok(retype(outcome)) };
Ok(Outcome::Committed(Merged { part: part(&merged.part)?, rows: Some(merged.rows), bytes: Some(merged.bytes) }))
};
let account = |outcome: &Outcome<Merged>, work: &mut Work| {
if let Outcome::Committed(merged) = outcome {
work.parts_committed = 1;
work.parts_merged = candidate.sources.len() as u64;
work.part_rows = merged.rows.unwrap_or_default();
work.part_bytes = merged.bytes.unwrap_or_default();
}
ended(outcome)
};
self.operate(Kind::Merge, Some(table), pb::request::Operation::Merge(operation), None, read, account).await
}
async fn housekeep(&self, table: &TableName) -> Result<Outcome<Housekept>, Error> {
let read = |response| {
let outcome = outcome(response, |result| match result {
pb::response::Result::Housekept(housekept) => Some(housekept),
_ => None,
})?;
let Outcome::Committed(housekept) = outcome else { return Ok(retype(outcome)) };
let temporary_directories = u64::from(housekept.temporary_directories_removed);
let removed = housekept.removed.iter().map(|name| part(name)).collect::<Result<_, _>>()?;
let remaining =
housekept.remaining.into_iter().map(|left| Ok(Remaining { part: part(&left.part)?, reason: left.reason })).collect::<Result<_, Error>>()?;
let (blobs_removed, blobs_remain) = (housekept.blobs_removed, housekept.blobs_remain);
Ok(Outcome::Committed(Housekept { removed, remaining, temporary_directories, blobs_removed, blobs_remain }))
};
let account = |outcome: &Outcome<Housekept>, work: &mut Work| {
if let Outcome::Committed(housekept) = outcome {
work.parts_removed = housekept.removed.len() as u64;
work.blobs_removed = housekept.blobs_removed;
}
ended(outcome)
};
self.operate(Kind::Housekeep, Some(table), pb::request::Operation::Housekeep(pb::Housekeep { table: pb_table(table) }), None, read, account).await
}
}
fn ended<T>(outcome: &Outcome<T>) -> Ended {
match outcome {
Outcome::Committed(_) => Ended::Committed,
Outcome::Duplicate => Ended::Duplicate,
Outcome::SchemaChanged => Ended::SchemaChanged,
Outcome::Fenced => Ended::Fenced,
Outcome::ClaimLost => Ended::ClaimLost,
Outcome::Refused(_) => Ended::Refused,
}
}
fn retype<T, U>(outcome: Outcome<T>) -> Outcome<U> {
match outcome {
Outcome::Committed(_) => unreachable!("a committed outcome carries its own result"),
Outcome::Duplicate => Outcome::Duplicate,
Outcome::SchemaChanged => Outcome::SchemaChanged,
Outcome::Fenced => Outcome::Fenced,
Outcome::ClaimLost => Outcome::ClaimLost,
Outcome::Refused(reason) => Outcome::Refused(reason),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn response(status: pb::Status) -> pb::Response {
pb::Response { status: status as i32, ..pb::Response::default() }
}
fn inserted(result: pb::response::Result) -> Option<pb::Inserted> {
match result {
pb::response::Result::Inserted(inserted) => Some(inserted),
_ => None,
}
}
#[test]
fn statuses_become_outcomes() {
let ok = pb::Response { result: Some(pb::response::Result::Inserted(pb::Inserted::default())), ..response(pb::Status::Ok) };
assert!(outcome(ok, inserted).unwrap().is_committed());
assert_eq!(outcome(response(pb::Status::Duplicate), inserted).unwrap(), Outcome::Duplicate);
assert_eq!(outcome(response(pb::Status::SchemaChanged), inserted).unwrap(), Outcome::SchemaChanged);
assert_eq!(outcome(response(pb::Status::Fenced), inserted).unwrap(), Outcome::Fenced);
assert_eq!(outcome(response(pb::Status::ClaimLost), inserted).unwrap(), Outcome::ClaimLost);
let refused = pb::Response { message: "no tokens".into(), ..response(pb::Status::Refused) };
assert_eq!(outcome(refused, inserted).unwrap(), Outcome::Refused("no tokens".into()));
}
#[test]
fn failures_and_malformed_answers_become_errors() {
let exception = pb::Response { message: "Table d.t does not exist".into(), exception_code: 60, ..response(pb::Status::Failed) };
assert_eq!(outcome(exception, inserted).unwrap_err().clickhouse_code(), Some(60));
let failed = pb::Response { message: "out of memory".into(), ..response(pb::Status::Failed) };
assert!(matches!(outcome(failed, inserted).unwrap_err(), Error::Worker { message } if message.contains("out of memory")));
assert!(outcome(response(pb::Status::Ok), inserted).is_err(), "OK needs a result");
let wrong = pb::Response { result: Some(pb::response::Result::Merged(pb::Merged::default())), ..response(pb::Status::Ok) };
assert!(outcome(wrong, inserted).is_err(), "OK needs this operation's result");
assert!(outcome(response(pb::Status::Unspecified), inserted).is_err());
assert!(outcome(pb::Response { status: 99, ..pb::Response::default() }, inserted).is_err());
}
#[test]
fn an_answer_is_one_whole_frame_from_a_clean_exit() {
let ok = ExitStatus::from_raw(0);
let frame = pb::message_frame(&response(pb::Status::Duplicate));
assert_eq!(decode(ok, &frame).unwrap().status, pb::Status::Duplicate as i32);
let failed = |status, answer: &[u8], expected: Failure, words: &str| {
let (failure, problem) = decode(status, answer).unwrap_err();
assert_eq!(failure, expected, "{problem}");
assert!(problem.contains(words), "{problem}");
};
failed(ExitStatus::from_raw(3 << 8), &frame, Failure::Exited, "failed with");
failed(ExitStatus::from_raw(9), &frame, Failure::Exited, "failed with");
failed(ok, b"", Failure::Exited, "without a response");
failed(ok, &frame[..frame.len() - 1], Failure::Protocol, "one response frame");
let mut twice = frame.clone();
twice.extend_from_slice(&frame);
failed(ok, &twice, Failure::Protocol, "one response frame");
failed(ok, b"Code: 60. DB::Exception: no such table", Failure::Protocol, "no response frame");
let mut garbled = 3u32.to_le_bytes().to_vec();
garbled.extend_from_slice(&[0xff, 0xff, 0xff]);
failed(ok, &garbled, Failure::Protocol, "does not decode");
}
#[test]
fn usage_sums_calls_and_keeps_peaks() {
let mut usage = Usage::default();
let worker = |commits, memory, threads| pb::Usage {
inodedb_commits: commits,
inodedb_stats: 2,
inodedb_reads: 3,
inodedb_lists: 1,
s3_reads: 4,
s3_writes: 5,
cpu_microseconds: 1_500,
anonymous_memory_bytes: memory,
threads,
inodedb_microseconds: 2_000,
inodedb_retries: 1,
s3_read_microseconds: 300,
s3_write_microseconds: 700,
s3_throttled: 1,
s3_bytes_read: 10,
s3_bytes_written: 20,
};
usage += Usage::of(&worker(2, 40 << 20, 9));
usage += Usage::of(&worker(1, 30 << 20, 12));
assert_eq!((usage.operations, usage.inodedb_commits, usage.inodedb_calls()), (2, 3, 15));
assert_eq!((usage.s3_reads, usage.s3_writes, usage.cpu), (8, 10, Duration::from_millis(3)));
assert_eq!((usage.peak_anonymous_memory_bytes, usage.peak_threads), (40 << 20, 12));
assert_eq!((usage.inodedb_time, usage.inodedb_retries), (Duration::from_millis(4), 2));
assert_eq!((usage.s3_read_time, usage.s3_write_time, usage.s3_throttled), (Duration::from_micros(600), Duration::from_micros(1_400), 2));
assert_eq!((usage.s3_bytes_read, usage.s3_bytes_written), (20, 40));
}
#[test]
fn the_command_names_the_fork_worker() {
let command = WorkerCommand::clickhouse("/opt/bighouse/clickhouse").env("TZ", "UTC");
assert_eq!(command.program, PathBuf::from("/opt/bighouse/clickhouse"));
assert_eq!(command.args, ["libch-worker"]);
assert_eq!(command.envs, [("TZ".to_string(), "UTC".to_string())]);
assert_eq!(command.arguments(Path::new("/scratch/w1")), ["libch-worker", "--path=/scratch/w1"]);
}
#[test]
fn a_sandbox_names_its_ports_and_paths_to_the_worker() {
let sandbox = Sandbox::reaching("10.0.0.5:7170", "https://s3.us-east-1.amazonaws.com").unwrap();
assert_eq!(sandbox.connect_ports, [7170, 443]);
assert_eq!(Sandbox::reaching("127.0.0.1:7170", "http://127.0.0.1:11211").unwrap().connect_ports, [7170, 11211]);
assert!(Sandbox::reaching("inodedb", "http://127.0.0.1:11211").is_err(), "a store without a port");
let sandbox = Sandbox { read_paths: vec!["/etc/corp-ca.pem".into()], ..sandbox };
let command = WorkerCommand::clickhouse("/opt/bighouse/clickhouse").sandboxed(sandbox);
assert_eq!(
command.arguments(Path::new("/scratch/w1")),
["libch-worker", "--path=/scratch/w1", "--sandbox", "--allow-connect=7170,443", "--allow-read=/etc/corp-ca.pem"]
);
}
#[test]
fn probes_name_themselves_and_read_their_outcomes() {
assert_eq!(Probe::Read("/etc/passwd".into()).argument(), "--probe-read=/etc/passwd");
assert_eq!(Probe::Connect("127.0.0.1:9000".parse().unwrap()).argument(), "--probe-connect=127.0.0.1:9000");
assert_eq!(Probe::Signal(1).argument(), "--probe-signal=1");
assert_eq!(probe_outcome("ok"), Some(None));
assert_eq!(probe_outcome("13 Permission denied"), Some(Some(13)));
assert_eq!(probe_outcome("denied"), None);
}
#[test]
fn a_scratch_directory_goes_with_its_value() {
let base = std::env::temp_dir().join(format!("libch-scratch-test-{:08x}", rand::random::<u32>()));
let scratch = Scratch::make(&base).unwrap();
let path = scratch.path().to_path_buf();
assert!(path.is_dir() && path.starts_with(&base));
drop(scratch);
assert!(!path.exists());
std::fs::remove_dir(&base).unwrap();
}
#[test]
fn a_log_tail_is_empty_for_a_quiet_worker() {
assert_eq!(log_tail(" \n"), "");
assert_eq!(log_tail("one line\n"), "; its log ends: one line");
assert!(log_tail(&"x".repeat(5_000)).len() < 2_100);
}
}