diff --git a/.github/check-for-naughty-dependencies.sh b/.github/check-for-naughty-dependencies.sh new file mode 100644 index 00000000..2e4d9632 --- /dev/null +++ b/.github/check-for-naughty-dependencies.sh @@ -0,0 +1,13 @@ +echo "Checking for openssl-sys in dependency tree..." +if cargo tree -i openssl-sys >/dev/null 2>&1; then + echo "openssl-sys is present in the dependency tree. Please evict it." + exit 1 +fi + +echo "Checking for native-tls in dependency tree..." +if cargo tree -i native-tls >/dev/null 2>&1; then + echo "native-tls is present in the dependency tree. Please evict it." + exit 1 +fi + +echo "✅ No naughty dependencies found" diff --git a/.github/workflows/test-rust.yml b/.github/workflows/test-rust.yml index 8268147f..044d7125 100644 --- a/.github/workflows/test-rust.yml +++ b/.github/workflows/test-rust.yml @@ -51,6 +51,8 @@ jobs: env: RUST_LOG: debug + - run: bash .github/check-for-naughty-dependencies.sh + # integration-test: # runs-on: ${{ matrix.os }} # strategy: diff --git a/Cargo.lock b/Cargo.lock index 2e545ea4..6e25f5b2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -140,11 +140,27 @@ checksum = "59a194f9d963d8099596278594b3107448656ba73831c9d8c783e613ce86da64" dependencies = [ "flate2", "futures-core", + "futures-io", "memchr", "pin-project-lite", "tokio", ] +[[package]] +name = "async_zip" +version = "0.0.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527207465fb6dcafbf661b0d4a51d0d2306c9d0c2975423079a6caa807930daf" +dependencies = [ + "async-compression", + "crc32fast", + "futures-lite", + "pin-project", + "thiserror 1.0.69", + "tokio", + "tokio-util", +] + [[package]] name = "autocfg" version = "1.4.0" @@ -675,6 +691,12 @@ dependencies = [ "str-buf", ] +[[package]] +name = "fastrand" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" + [[package]] name = "fd-lock" version = "3.0.13" @@ -771,6 +793,19 @@ version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9e5c1b78ca4aae1ac06c48a526a655760685149f0d465d21f37abfe57ce075c6" +[[package]] +name = "futures-lite" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5edaec856126859abb19ed65f39e90fea3a9574b9707f13539acf4abf7eb532" +dependencies = [ + "fastrand", + "futures-core", + "futures-io", + "parking", + "pin-project-lite", +] + [[package]] name = "futures-macro" version = "0.3.31" @@ -1563,6 +1598,12 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39" +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + [[package]] name = "parking_lot" version = "0.12.3" @@ -1611,6 +1652,26 @@ version = "2.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" +[[package]] +name = "pin-project" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "677f1add503faace112b9f1373e43e9e054bfdd22ff1a63c1bc485eaec6a6a8a" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e918e4ff8c4549eb882f14b3a4bc8c8bc93de829416eacf579f1207a8fbf861" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.100", +] + [[package]] name = "pin-project-lite" version = "0.2.16" @@ -1747,7 +1808,7 @@ dependencies = [ "once_cell", "socket2", "tracing", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -2648,6 +2709,7 @@ checksum = "6b9590b93e6fcc1739458317cccd391ad3955e2bde8913edf6f95f9e65a8f034" dependencies = [ "bytes", "futures-core", + "futures-io", "futures-sink", "pin-project-lite", "tokio", @@ -2787,8 +2849,10 @@ dependencies = [ "chrono", "snafu", "tokio", + "tokio-util", "tower-package", "tower-telemetry", + "tower-uv", ] [[package]] @@ -2806,6 +2870,19 @@ dependencies = [ "tracing-subscriber", ] +[[package]] +name = "tower-uv" +version = "0.3.20" +dependencies = [ + "async-compression", + "async_zip", + "futures-lite", + "reqwest", + "tokio", + "tokio-tar", + "tower-telemetry", +] + [[package]] name = "tower-version" version = "0.3.20" diff --git a/Cargo.toml b/Cargo.toml index 151b0644..116d1a0d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,6 +15,7 @@ repository = "https://github.com/tower/tower-cli" aes-gcm = "0.10" anyhow = "1.0.95" async-compression = { version = "0.4", features = ["tokio", "gzip"] } +async_zip = { version = "0.0.16", features = ["tokio", "tokio-fs", "deflate"] } base64 = "0.22" bytes = "1" chrono = { version = "0.4", features = ["serde"] } @@ -26,6 +27,7 @@ crypto = { path = "crates/crypto" } dirs = "5" futures = "0.3" futures-util = "0.3" +futures-lite = "2.6" glob = "0.3" http = "1.1" indicatif = "0.17" @@ -53,6 +55,7 @@ tower-cmd = { path = "crates/tower-cmd" } tower-package = { path = "crates/tower-package" } tower-runtime = { path = "crates/tower-runtime" } tower-telemetry = { path = "crates/tower-telemetry" } +tower-uv = { path = "crates/tower-uv" } tracing = { version = "0.1" } tracing-appender = "0.2" tracing-subscriber = { version = "0.3", features = ["json", "env-filter"] } diff --git a/crates/tower-runtime/Cargo.toml b/crates/tower-runtime/Cargo.toml index 184a5be6..99770ec3 100644 --- a/crates/tower-runtime/Cargo.toml +++ b/crates/tower-runtime/Cargo.toml @@ -9,6 +9,8 @@ license = { workspace = true } [dependencies] chrono = { workspace = true } tokio = { workspace = true } +tokio-util = { workspace = true } snafu = { workspace = true } tower-package = { workspace = true } tower-telemetry = { workspace = true } +tower-uv = { workspace = true } diff --git a/crates/tower-runtime/src/errors.rs b/crates/tower-runtime/src/errors.rs index 78ac4785..5162fc6d 100644 --- a/crates/tower-runtime/src/errors.rs +++ b/crates/tower-runtime/src/errors.rs @@ -61,6 +61,9 @@ pub enum Error { #[snafu(display("running Tower apps on this platform is not supported"))] UnsupportedPlatform, + + #[snafu(display("cancelled"))] + Cancelled, } impl From for Error { @@ -74,3 +77,14 @@ impl From for Error { Error::UnsupportedPlatform } } + +impl From for Error { + fn from(err: tower_uv::Error) -> Self { + match err { + tower_uv::Error::IoError(_) => Error::SpawnFailed, + tower_uv::Error::NotFound(_) => Error::SpawnFailed, + tower_uv::Error::PermissionDenied(_) => Error::SpawnFailed, + tower_uv::Error::Other(_) => Error::SpawnFailed, + } + } +} diff --git a/crates/tower-runtime/src/local.rs b/crates/tower-runtime/src/local.rs index 9a82efd4..76c16124 100644 --- a/crates/tower-runtime/src/local.rs +++ b/crates/tower-runtime/src/local.rs @@ -1,7 +1,6 @@ -use std::path::{Path, PathBuf}; +use std::path::PathBuf; use std::env; use std::process::Stdio; -use std::sync::Arc; use std::collections::HashMap; #[cfg(unix)] @@ -17,15 +16,23 @@ use crate::{ use tokio::{ fs, io::{AsyncRead, BufReader, AsyncBufReadExt}, - time::{timeout, Duration}, - sync::Mutex, process::{Child, Command}, - sync::oneshot, - sync::oneshot::error::TryRecvError, + sync::{ + Mutex, + oneshot::{ + self, + error::TryRecvError, + }, + }, + task::JoinHandle, + time::{timeout, Duration}, }; +use tokio_util::sync::CancellationToken; + use tower_package::{Manifest, Package}; use tower_telemetry::debug; +use tower_uv::Uv; use crate::{ FD, @@ -35,17 +42,17 @@ use crate::{ }; pub struct LocalApp { - ctx: tower_telemetry::Context, - - // LocalApp needs to take ownership of the package as a way of taking responsibility for it's - // lifetime and, most importantly, it's contents. The compiler complains that we never actually - // use this struct member, so we allow the dead_code attribute to silence the warning. - #[allow(dead_code)] - package: Option, - - child: Option>>, status: Mutex>, + + // waiter is what we use to communicate that the overall process is finished by the execution + // handle. waiter: Mutex>, + + // terminator is what we use to flag that we want to terminate the child process. + terminator: Mutex, + + // execute_handle keeps track of the current state of the execution lifecycle. + execute_handle: Option>>, } // Helper function to check if a file is executable @@ -90,32 +97,6 @@ async fn find_executable_in_path(executable_name: &str) -> Option { None } -async fn find_pip(dir: PathBuf) -> Result { - if let Some(path) = find_executable_in_path_buf("pip", dir).await { - Ok(path) - } else { - Err(Error::MissingPip) - } -} - -async fn find_python(dir: Option) -> Result { - if let Some(dir) = dir { - // find a local python - if let Some(path) = find_executable_in_path_buf("python", dir).await { - Ok(path) - } else { - Err(Error::MissingPython) - } - } else { - // find the system installed python - if let Some(path) = find_executable_in_path("python").await { - Ok(path) - } else { - Err(Error::MissingPython) - } - } -} - async fn find_bash() -> Result { if let Some(path) = find_executable_in_path("bash").await { Ok(path) @@ -124,168 +105,152 @@ async fn find_bash() -> Result { } } +async fn execute_local_app(opts: StartOptions, sx: oneshot::Sender, cancel_token: CancellationToken) -> Result<(), Error> { + let ctx = opts.ctx.clone(); + let package = opts.package; + let environment = opts.environment; + let package_path = package.unpacked_path + .clone() + .unwrap() + .to_path_buf(); + + // set for later on. + let working_dir = if package.manifest.version == Some(2) { + package_path.join(&package.manifest.app_dir_name) + } else { + package_path.to_path_buf() + }; -impl App for LocalApp { - async fn start(opts: StartOptions) -> Result { - let ctx = opts.ctx.clone(); - let package = opts.package; - let environment = opts.environment; - debug!(ctx: &ctx, "executing app with version {:?}", package.manifest.version); - - // This is the base path of where the package was unpacked. - let package_path = package.unpacked_path - .clone() - .unwrap() - .to_path_buf(); - - // We'll need the Python path for later on. - let mut python_path = find_python(None).await?; - debug!(ctx: &ctx, "using system python at {:?}", python_path); - - // set for later on. - let working_dir = if package.manifest.version == Some(2) { - package_path.join(&package.manifest.app_dir_name) - } else { - opts.cwd.unwrap_or(package_path.to_path_buf()) - }; - - let mut is_virtualenv = false; - - if Path::new(&working_dir.join("requirements.txt")).exists() { - debug!(ctx: &ctx, "requirements.txt file found. installing dependencies"); - - // There's a requirements.txt, so we'll create a new virtualenv and install the files - // taht we want in there. - let res = Command::new(python_path) - .current_dir(&working_dir) - .arg("-m") - .arg("venv") - .arg(".venv") - .kill_on_drop(true) - .spawn(); - - if let Ok(mut child) = res { - // Wait for the child to complete entirely. - child.wait().await.expect("child failed to exit"); - } else { - return Err(Error::VirtualEnvCreationFailed); - } + debug!(ctx: &ctx, " - working directory: {:?}", &working_dir); - let pip_path = find_pip(working_dir.join(".venv").join("bin")).await?; + let manifest = &package.manifest; + let secrets = opts.secrets; + let params = opts.parameters; + let mut other_env_vars = opts.env_vars; - // We need to update our local python, too - // - // TODO: Find a better way to operate in the context of a virtual env here. - python_path = find_python(Some(working_dir.join(".venv").join("bin"))).await?; - debug!(ctx: &ctx, "using virtualenv python at {:?}", python_path); + if !package.manifest.import_paths.is_empty() { + debug!(ctx: &ctx, "adding import paths to PYTHONPATH: {:?}", package.manifest.import_paths); - is_virtualenv = true; + let import_paths = package.manifest.import_paths + .iter() + .map(|p| package_path.join(p)) + .collect::>(); - let res = Command::new(pip_path) - .current_dir(&working_dir) - .arg("install") - .arg("-r") - .arg(working_dir.join("requirements.txt")) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .kill_on_drop(true) - .spawn(); + let import_paths = std::env::join_paths(import_paths)? + .to_string_lossy() + .to_string(); - if let Ok(mut child) = res { - if let Some(ref sender) = opts.output_sender { - // Let's also send our logs to this output channel. - let stdout = child.stdout.take().expect("no stdout"); - tokio::spawn(drain_output(FD::Stdout, Channel::Setup, sender.clone(), BufReader::new(stdout))); + if other_env_vars.contains_key("PYTHONPATH") { + // If we already have a PYTHONPATH, we need to append to it. + let existing = other_env_vars.get("PYTHONPATH").unwrap(); + let pythonpath = std::env::join_paths(vec![existing, &import_paths])? + .to_string_lossy() + .to_string(); - let stderr = child.stderr.take().expect("no stderr"); - tokio::spawn(drain_output(FD::Stderr, Channel::Setup, sender.clone(), BufReader::new(stderr))); + other_env_vars.insert("PYTHONPATH".to_string(), pythonpath); + } else { + // Otherwise, we just set it. + other_env_vars.insert("PYTHONPATH".to_string(), import_paths); + } + } - } + // We insert these checks for cancellation along the way to see if the process was + // terminated by someone. + // + // We do this before instantiating `Uv` because that can be somewhat time consuming. Likewise + // this stops us from instantiating a bash process. + if cancel_token.is_cancelled() { + // if there's a waiter, we want them to know that the process was cancelled so we have + // to return something on the relevant channel. + let _ = sx.send(-1); + return Err(Error::Cancelled); + } - debug!(ctx: &ctx, "waiting for dependency installation to complete"); + if is_bash_package(&package) { + let child = execute_bash_program( + &ctx, + &environment, + working_dir, + package_path, + &manifest, + secrets, + params, + other_env_vars, + ).await?; + + let _ = sx.send(wait_for_process(ctx.clone(), &cancel_token, child).await); + } else { + let uv = Uv::new().await?; + let env_vars = make_env_vars(&ctx, &environment, &package_path, &secrets, ¶ms, &other_env_vars); + + // Now we also need to find the program to execute. + let program_path = working_dir.join(&manifest.invoke); + + // Check once more if the process was cancelled before we do a uv sync. The sync itself, + // once started, will take a while and we have logic for checking for cancellation. + if cancel_token.is_cancelled() { + // again tell any waiters that we cancelled. + let _ = sx.send(-1); + return Err(Error::Cancelled); + } - // Wait for the child to complete entirely. - child.wait().await.expect("child failed to exit"); - } - } else { - debug!(ctx: &ctx, "missing requirements.txt file found. no dependencies to install"); + let mut child = uv.sync(&working_dir, &env_vars).await?; + + // Drain the logs to the output channel. + if let Some(ref sender) = opts.output_sender { + let stdout = child.stdout.take().expect("no stdout"); + tokio::spawn(drain_output(FD::Stdout, Channel::Setup, sender.clone(), BufReader::new(stdout))); + + let stderr = child.stderr.take().expect("no stderr"); + tokio::spawn(drain_output(FD::Stderr, Channel::Setup, sender.clone(), BufReader::new(stderr))); } - debug!(ctx: &ctx, " - working directory: {:?}", &working_dir); + // Let's wait for the setup to finish. We don't care about the results. + wait_for_process(ctx.clone(), &cancel_token, child).await; - let res = if package.manifest.invoke.ends_with(".sh") { - let manifest = &package.manifest; - let secrets = opts.secrets; - let params= opts.parameters; - let other_env_vars = opts.env_vars; + // Check once more to see if the process was cancelled, this will bail us out early. + if cancel_token.is_cancelled() { + // if there's a waiter, we want them to know that the process was cancelled so we have + // to return something on the relevant channel. + let _ = sx.send(-1); + return Err(Error::Cancelled); + } - Self::execute_bash_program(&ctx, &environment, working_dir, is_virtualenv, package_path, &manifest, secrets, params, other_env_vars).await - } else { - let manifest = &package.manifest; - let secrets = opts.secrets; - let params= opts.parameters; - let mut other_env_vars = opts.env_vars; - - if !package.manifest.import_paths.is_empty() { - debug!(ctx: &ctx, "adding import paths to PYTHONPATH: {:?}", package.manifest.import_paths); - - let import_paths = package.manifest.import_paths - .iter() - .map(|p| package_path.join(p)) - .collect::>(); - - let import_paths = std::env::join_paths(import_paths)? - .to_string_lossy() - .to_string(); - - if other_env_vars.contains_key("PYTHONPATH") { - // If we already have a PYTHONPATH, we need to append to it. - let existing = other_env_vars.get("PYTHONPATH").unwrap(); - let pythonpath = std::env::join_paths(vec![existing, &import_paths])? - .to_string_lossy() - .to_string(); - - other_env_vars.insert("PYTHONPATH".to_string(), pythonpath); - } else { - // Otherwise, we just set it. - other_env_vars.insert("PYTHONPATH".to_string(), import_paths); - } - } + let mut child = uv.run(&working_dir, &program_path, &env_vars).await?; - // We need to resolve the program - let program_path = working_dir.join(manifest.invoke.clone()); + // Drain the logs to the output channel. + if let Some(ref sender) = opts.output_sender { + let stdout = child.stdout.take().expect("no stdout"); + tokio::spawn(drain_output(FD::Stdout, Channel::Program, sender.clone(), BufReader::new(stdout))); - Self::execute_python_program(&ctx, &environment, working_dir, is_virtualenv, python_path, program_path, &manifest, secrets, params, other_env_vars).await - }; + let stderr = child.stderr.take().expect("no stderr"); + tokio::spawn(drain_output(FD::Stderr, Channel::Program, sender.clone(), BufReader::new(stderr))); + } - if let Ok(mut child) = res { - if let Some(ref sender) = opts.output_sender { - // Let's also send our logs to this output channel. - let stdout = child.stdout.take().expect("no stdout"); - tokio::spawn(drain_output(FD::Stdout, Channel::Setup, sender.clone(), BufReader::new(stdout))); + let _ = sx.send(wait_for_process(ctx.clone(), &cancel_token, child).await); + } - let stderr = child.stderr.take().expect("no stderr"); - tokio::spawn(drain_output(FD::Stderr, Channel::Setup, sender.clone(), BufReader::new(stderr))); + // Everything was properly executed I suppose. + return Ok(()) +} - } +impl App for LocalApp { + async fn start(opts: StartOptions) -> Result { + let cancel_token = CancellationToken::new(); + let terminator = Mutex::new(cancel_token.clone()); - let child = Arc::new(Mutex::new(child)); - let (sx, rx) = oneshot::channel::(); + let (sx, rx) = oneshot::channel::(); + let waiter = Mutex::new(rx); - tokio::spawn(wait_for_process(ctx.clone(), sx, Arc::clone(&child))); + let handle = tokio::spawn(execute_local_app(opts, sx, cancel_token)); + let execute_handle = Some(handle); - Ok(Self { - ctx, - package: Some(package), - child: Some(child), - waiter: Mutex::new(rx), - status: Mutex::new(None), - }) - } else { - debug!(ctx: &ctx, "failed to spawn process: {}", res.err().unwrap()); - Err(Error::SpawnFailed) - } + Ok(Self { + execute_handle, + terminator, + waiter, + status: Mutex::new(None), + }) } async fn status(&self) -> Result { @@ -316,90 +281,45 @@ impl App for LocalApp { } async fn terminate(&mut self) -> Result<(), Error> { - if let Some(proc) = &mut self.child { - let mut child = proc.lock().await; + let terminator = self.terminator.lock().await; + terminator.cancel(); - if let Err(err) = child.kill().await { - debug!(ctx: &self.ctx, "failed to terminate app: {}", err); - Err(Error::TerminateFailed) - } else { - Ok(()) - } - } else { - // Nothing to terminate. Should this be an error? - Ok(()) - } - } -} + // Now we should wait for the join handle to finish. + if let Some(execute_handle) = self.execute_handle.take() { + let _ = execute_handle.await; + self.execute_handle = None; + } -impl LocalApp { - async fn execute_python_program( - ctx: &tower_telemetry::Context, - env: &str, - cwd: PathBuf, - is_virtualenv: bool, - python_path: PathBuf, - program_path: PathBuf, - manifest: &Manifest, - secrets: HashMap, - params: HashMap, - other_env_vars: HashMap, - ) -> Result { - let env_vars = make_env_vars( - &ctx, - env, - &cwd, - is_virtualenv, - &secrets, - ¶ms, - &other_env_vars, - ); - - debug!(ctx: &ctx, " - python script {}", manifest.invoke); - debug!(ctx: &ctx, " - python path {}", env_vars.get("PYTHONPATH").unwrap()); - - let child = Command::new(python_path) - .current_dir(&cwd) - .arg("-u") - .arg(program_path) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .envs(env_vars) - .kill_on_drop(true) - .spawn()?; - - Ok(child) + Ok(()) } +} - async fn execute_bash_program( - ctx: &tower_telemetry::Context, - env: &str, - cwd: PathBuf, - is_virtualenv: bool, - package_path: PathBuf, - manifest: &Manifest, - secrets: HashMap, - params: HashMap, - other_env_vars: HashMap, - ) -> Result { - let bash_path = find_bash().await?; - debug!(ctx: &ctx, "using bash at {:?}", bash_path); - - debug!(ctx: &ctx, " - bash script {}", manifest.invoke); - - let child = Command::new(bash_path) - .current_dir(&cwd) - .arg(package_path.join(manifest.invoke.clone())) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .envs(make_env_vars(&ctx, env, &cwd, is_virtualenv, &secrets, ¶ms, &other_env_vars)) - .kill_on_drop(true) - .spawn()?; - - Ok(child) - } +async fn execute_bash_program( + ctx: &tower_telemetry::Context, + env: &str, + cwd: PathBuf, + package_path: PathBuf, + manifest: &Manifest, + secrets: HashMap, + params: HashMap, + other_env_vars: HashMap, +) -> Result { + let bash_path = find_bash().await?; + debug!(ctx: &ctx, "using bash at {:?}", bash_path); + + debug!(ctx: &ctx, " - bash script {}", manifest.invoke); + + let child = Command::new(bash_path) + .current_dir(&cwd) + .arg(package_path.join(manifest.invoke.clone())) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .envs(make_env_vars(&ctx, env, &cwd, &secrets, ¶ms, &other_env_vars)) + .kill_on_drop(true) + .spawn()?; + + Ok(child) } fn make_env_var_key(src: &str) -> String { @@ -411,7 +331,7 @@ fn make_env_var_key(src: &str) -> String { } } -fn make_env_vars(ctx: &tower_telemetry::Context, env: &str, cwd: &PathBuf, is_virtualenv: bool, secs: &HashMap, params: &HashMap, other_env_vars: &HashMap) -> HashMap { +fn make_env_vars(ctx: &tower_telemetry::Context, env: &str, cwd: &PathBuf, secs: &HashMap, params: &HashMap, other_env_vars: &HashMap) -> HashMap { let mut res = HashMap::new(); debug!(ctx: &ctx, "converting {} env variables", (params.len() + secs.len())); @@ -431,28 +351,6 @@ fn make_env_vars(ctx: &tower_telemetry::Context, env: &str, cwd: &PathBuf, is_vi res.insert(key.to_string(), value.to_string()); } - // If we're in a virtual environment, we need to add the bin directory to the PATH so that we - // can find any executables that were installed there. - if is_virtualenv { - let venv_dir = cwd.join(".venv"); - let venv_path = venv_dir - .to_string_lossy() - .to_string(); - - let bin_path = venv_dir.join("bin") - .to_string_lossy() - .to_string(); - - if let Ok(path) = std::env::var("PATH") { - res.insert("PATH".to_string(), format!("{}:{}", bin_path, path)); - } else { - res.insert("PATH".to_string(), bin_path); - } - - // We also insert a VIRTUAL_ENV path such that we can - res.insert("VIRTUAL_ENV".to_string(), venv_path); - } - // We also need a PYTHONPATH that is set to the current working directory to help with the // dependency resolution problem at runtime. let pythonpath = cwd.to_string_lossy().to_string(); @@ -476,16 +374,22 @@ fn make_env_vars(ctx: &tower_telemetry::Context, env: &str, cwd: &PathBuf, is_vi res.insert("TOWER_ENVIRONMENT".to_string(), env.to_string()); } + res.insert("PYTHONUNBUFFERED".to_string(), "x".to_string()); + res } -async fn wait_for_process(ctx: tower_telemetry::Context, sx: oneshot::Sender, proc: Arc>) { +async fn wait_for_process(ctx: tower_telemetry::Context, cancel_token: &CancellationToken, mut child: Child) -> i32 { let code = loop { - let mut child = proc.lock().await; - let timeout = timeout(Duration::from_millis(250), child.wait()).await; + if cancel_token.is_cancelled() { + debug!(ctx: &ctx, "process cancelled, terminating child process"); + let _ = child.kill().await; + break -1; // return -1 to indicate that the process was cancelled. + } - if let Ok(res) = timeout { + let timeout = timeout(Duration::from_millis(25), child.wait()).await; + if let Ok(res) = timeout { if let Ok(status) = res { break status.code().expect("no status code"); } else { @@ -499,7 +403,7 @@ async fn wait_for_process(ctx: tower_telemetry::Context, sx: oneshot::Sender(fd: FD, channel: Channel, output: OutputSender, input: BufReader) { @@ -517,3 +421,7 @@ async fn drain_output(fd: FD, channel: Channel, output: Ou } } + +fn is_bash_package(package: &Package) -> bool { + return package.manifest.invoke.ends_with(".sh") +} diff --git a/crates/tower-uv/Cargo.toml b/crates/tower-uv/Cargo.toml new file mode 100644 index 00000000..ffd63f59 --- /dev/null +++ b/crates/tower-uv/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "tower-uv" +version = { workspace = true } +authors = { workspace = true } +edition = { workspace = true } +rust-version = { workspace = true } +license = { workspace = true } + +[dependencies] +async-compression = { workspace = true } +async_zip = { workspace = true } +futures-lite = { workspace = true } +reqwest = { workspace = true } +tokio = { workspace = true } +tokio-tar = { workspace = true } +tower-telemetry = { workspace = true } diff --git a/crates/tower-uv/src/install.rs b/crates/tower-uv/src/install.rs new file mode 100644 index 00000000..25677da3 --- /dev/null +++ b/crates/tower-uv/src/install.rs @@ -0,0 +1,308 @@ +use std::env; +use std::path::PathBuf; + +use tokio_tar::Archive; +use tokio::process::Command; +use async_compression::tokio::bufread::GzipDecoder; +use async_zip::tokio::read::seek::ZipFileReader; +use futures_lite::io::AsyncReadExt; + +use tower_telemetry::debug; + +// Copy the UV_VERSION locally to make this a bit more ergonomic. +const UV_VERSION: &str = crate::UV_VERSION; + +#[derive(Debug)] +pub enum Error { + IoError(std::io::Error), + Other(String), +} + +impl From for Error { + fn from(err: std::io::Error) -> Self { + Error::IoError(err) + } +} + +impl From for Error { + fn from(err: String) -> Self { + Error::Other(err) + } +} + +pub fn get_default_uv_bin_dir() -> Result { + Ok(PathBuf::from(".tower/bin")) +} + +#[derive(Debug)] +pub struct ArchiveSelector; + +impl ArchiveSelector { + /// Get the appropriate archive name for the current platform + pub async fn get_archive_name() -> Result { + let arch = env::consts::ARCH; + let os = env::consts::OS; + + match (arch, os) { + // macOS + ("aarch64", "macos") => Ok("uv-aarch64-apple-darwin.tar.gz".to_string()), + ("x86_64", "macos") => Ok("uv-x86_64-apple-darwin.tar.gz".to_string()), + + // Windows + ("aarch64", "windows") => Ok("uv-aarch64-pc-windows-msvc.zip".to_string()), + ("x86_64", "windows") => Ok("uv-x86_64-pc-windows-msvc.zip".to_string()), + ("x86", "windows") => Ok("uv-i686-pc-windows-msvc.zip".to_string()), + + // Linux + ("aarch64", "linux") => { + if Self::is_musl_target() { + Ok("uv-aarch64-unknown-linux-musl.tar.gz".to_string()) + } else if Self::check_glibc(2, 28).await { + Ok("uv-aarch64-unknown-linux-gnu.tar.gz".to_string()) + } else { + Ok("uv-aarch64-unknown-linux-musl.tar.gz".to_string()) + } + } + ("x86_64", "linux") => { + if Self::is_musl_target() { + Ok("uv-x86_64-unknown-linux-musl.tar.gz".to_string()) + } else if Self::check_glibc(2, 17).await { + Ok("uv-x86_64-unknown-linux-gnu.tar.gz".to_string()) + } else { + Ok("uv-x86_64-unknown-linux-musl.tar.gz".to_string()) + } + } + ("x86", "linux") => { + if Self::is_musl_target() { + Ok("uv-i686-unknown-linux-musl.tar.gz".to_string()) + } else if Self::check_glibc(2, 17).await { + Ok("uv-i686-unknown-linux-gnu.tar.gz".to_string()) + } else { + Ok("uv-i686-unknown-linux-musl.tar.gz".to_string()) + } + } + ("arm", "linux") => { + // ARM v6 - only musl available + Ok("uv-arm-unknown-linux-musleabihf.tar.gz".to_string()) + } + ("armv7", "linux") => { + if Self::is_musl_target() { + Ok("uv-armv7-unknown-linux-musleabihf.tar.gz".to_string()) + } else if Self::check_glibc(2, 17).await { + Ok("uv-armv7-unknown-linux-gnueabihf.tar.gz".to_string()) + } else { + Ok("uv-armv7-unknown-linux-musleabihf.tar.gz".to_string()) + } + } + ("powerpc64", "linux") => { + if Self::check_glibc(2, 17).await { + Ok("uv-powerpc64-unknown-linux-gnu.tar.gz".to_string()) + } else { + Err("PowerPC64 requires glibc 2.17 or newer".to_string()) + } + } + ("powerpc64le", "linux") => { + if Self::check_glibc(2, 17).await { + Ok("uv-powerpc64le-unknown-linux-gnu.tar.gz".to_string()) + } else { + Err("PowerPC64LE requires glibc 2.17 or newer".to_string()) + } + } + ("riscv64", "linux") => { + if Self::check_glibc(2, 31).await { + Ok("uv-riscv64gc-unknown-linux-gnu.tar.gz".to_string()) + } else { + Err("RISC-V 64 requires glibc 2.31 or newer".to_string()) + } + } + ("s390x", "linux") => { + if Self::check_glibc(2, 17).await { + Ok("uv-s390x-unknown-linux-gnu.tar.gz".to_string()) + } else { + Err("s390x requires glibc 2.17 or newer".to_string()) + } + } + + _ => Err(format!("Unsupported platform: {} {}", arch, os)), + } + } + + /// Check if the current target uses musl libc + fn is_musl_target() -> bool { + // Check if we're compiled with musl + cfg!(target_env = "musl") + } + + /// Check if glibc version meets minimum requirements + async fn check_glibc(major: u32, minor: u32) -> bool { + // Only check glibc on Linux with gnu env + if !cfg!(target_os = "linux") || cfg!(target_env = "musl") { + return false; + } + + // Try to get glibc version using ldd + if let Ok(output) = Command::new("ldd") + .arg("--version") + .output() + .await + { + if let Ok(version_str) = String::from_utf8(output.stdout) { + return Self::parse_glibc_version(&version_str, major, minor); + } + } + + // Fallback: try to read from /lib/libc.so.6 + if let Ok(output) = Command::new("/lib/libc.so.6") + .output() + .await + { + if let Ok(version_str) = String::from_utf8(output.stdout) { + return Self::parse_glibc_version(&version_str, major, minor); + } + } + + // If we can't determine the version, assume it's old + false + } + + /// Parse glibc version string and compare with required version + fn parse_glibc_version(version_str: &str, req_major: u32, req_minor: u32) -> bool { + // Look for version pattern like "2.17" or "2.31" + for line in version_str.lines() { + if let Some(version_part) = line.split_whitespace() + .find(|part| part.contains('.') && part.chars().next().unwrap_or('0').is_ascii_digit()) + { + let version_clean = version_part.trim_matches(|c: char| !c.is_ascii_digit() && c != '.'); + let parts: Vec<&str> = version_clean.split('.').collect(); + + if parts.len() >= 2 { + if let (Ok(major), Ok(minor)) = (parts[0].parse::(), parts[1].parse::()) { + return major > req_major || (major == req_major && minor >= req_minor); + } + } + } + } + false + } +} + +fn extract_package_name(archive: String) -> String { + // Remove .tar.gz or .zip extension + archive + .strip_suffix(".tar.gz") + .or(archive.strip_suffix(".zip")) + .unwrap_or(&archive) + .to_string() +} + +async fn download_uv_archive(path: &PathBuf, archive: String) -> Result { + debug!("Downloading UV archive: {}", archive); + let url = format!("https://github.com/astral-sh/uv/releases/download/{}/{}", UV_VERSION, archive); + + // Create the directory if it doesn't exist + std::fs::create_dir_all(&path).map_err(Error::IoError)?; + + // Download the file + let response = reqwest::get(url) + .await + .map_err(|e| Error::Other(e.to_string()))?; + + let bytes = response.bytes() + .await + .map_err(|e| Error::Other(e.to_string()))?; + + // Determine archive type from extension + if archive.ends_with(".tar.gz") { + let cursor = std::io::Cursor::new(bytes); + let tar = GzipDecoder::new(cursor); + + // Extract the tar.gz archive + Archive::new(tar) + .unpack(path) + .await?; + + let package_name = extract_package_name(archive.clone()); + Ok(path.join(package_name).join("uv")) + } else if archive.ends_with(".zip") { + // Write zip data to a temporary file since async-zip works with files + let temp_path = path.join("temp.zip"); + tokio::fs::write(&temp_path, bytes).await?; + + // Open the zip file using seek reader with compression support + let file = tokio::fs::File::open(&temp_path).await?; + let mut zip = ZipFileReader::with_tokio(file) + .await + .map_err(|e| Error::Other(format!("Failed to open zip file: {}", e)))?; + + let package_name = extract_package_name(archive.clone()); + let uv_path = "uv".to_string(); + let uv_exe_path = "uv.exe".to_string(); + + // Find the UV executable entry + let entries = zip.file().entries(); + let entry_index = entries + .iter() + .enumerate() + .find(|(_, entry)| { + let name = entry.filename().as_str().unwrap_or(""); + name == uv_path || name == uv_exe_path + }) + .map(|(index, _)| index) + .ok_or_else(|| Error::Other("UV executable not found in archive".to_string()))?; + + // Create the package directory + let target_dir = path.join(&package_name); + std::fs::create_dir_all(&target_dir)?; + + // Extract the file with proper error handling for compression + let filename = entries[entry_index].filename().as_str().unwrap_or("uv").to_string(); + let is_exe = filename.ends_with(".exe"); + let target_path = target_dir.join(if is_exe { "uv.exe" } else { "uv" }); + + let mut reader = zip.reader_with_entry(entry_index) + .await + .map_err(|e| Error::Other(format!("Failed to create entry reader for {}: {}", filename, e)))?; + let mut file = tokio::fs::File::create(&target_path).await?; + + // Manually copy data since ZipEntryReader doesn't implement AsyncRead + let mut buffer = [0u8; 8192]; + let mut total_bytes = 0; + loop { + let bytes_read = reader.read(&mut buffer) + .await + .map_err(|e| Error::Other(format!("Failed to read from zip entry: {}", e)))?; + if bytes_read == 0 { + break; + } + tokio::io::AsyncWriteExt::write_all(&mut file, &buffer[..bytes_read]) + .await + .map_err(|e| Error::Other(format!("Failed to write to output file: {}", e)))?; + total_bytes += bytes_read; + } + + debug!("Successfully extracted {} bytes to {:?}", total_bytes, target_path); + + // Make the file executable on Unix systems + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mut perms = std::fs::metadata(&target_path)?.permissions(); + perms.set_mode(0o755); + std::fs::set_permissions(&target_path, perms)?; + } + + // Clean up temporary zip file + tokio::fs::remove_file(temp_path).await?; + + Ok(target_path) + } else { + return Err(Error::Other(format!("Unsupported archive format: {}", archive))); + } +} + +pub async fn download_uv_for_arch(path: &PathBuf) -> Result { + let archive = ArchiveSelector::get_archive_name().await?; + let path = download_uv_archive(path, archive).await?; + debug!("Downloaded UV to: {:?}", path); + Ok(path) +} diff --git a/crates/tower-uv/src/lib.rs b/crates/tower-uv/src/lib.rs new file mode 100644 index 00000000..1998b21b --- /dev/null +++ b/crates/tower-uv/src/lib.rs @@ -0,0 +1,158 @@ +use std::path::PathBuf; +use std::collections::HashMap; +use std::process::Stdio; +use tokio::process::{Command, Child}; +use tower_telemetry::debug; + +mod install; + +// UV_VERSION is the version of UV to download and install when setting up a local UV deployment. +pub const UV_VERSION: &str = "0.7.13"; + +#[derive(Debug)] +pub enum Error { + IoError(std::io::Error), + NotFound(String), + PermissionDenied(String), + Other(String), +} + +impl From for Error { + fn from(err: std::io::Error) -> Self { + // Convert std::fs::Error to your custom Error type + Error::IoError(err) + } +} + +impl From for Error { + fn from(err: install::Error) -> Self { + match err { + install::Error::IoError(e) => Error::IoError(e), + install::Error::Other(msg) => Error::Other(msg), + } + } +} + +async fn find_uv_binary() -> Option { + if let Ok(default_path) = install::get_default_uv_bin_dir() { + // Check if the default path exists + if default_path.exists() { + let uv_path = default_path.join("uv"); + if uv_path.exists() { + return Some(uv_path); + } + } + } + + // First, check if uv is already in the PATH + let output = Command::new("which") + .arg("uv") + .output() + .await; + + if let Ok(output) = output { + let path_str = String::from_utf8_lossy(&output.stdout); + let path = PathBuf::from(path_str.trim()); + + // If this is a path that actually exists, then we assume that it's `uv` and we can + // continue. + if path.exists() { + Some(path) + } else { + None + } + } else { + None + } +} + +async fn find_or_setup_uv() -> Result { + // If we get here, uv wasn't found in PATH, so let's download it + if let Some(path) = find_uv_binary().await { + Ok(path) + } else { + let path = install::get_default_uv_bin_dir()?; + + // Create the directory if it doesn't exist + std::fs::create_dir_all(&path).map_err(Error::IoError)?; + + let parent = path.parent() + .ok_or_else(|| Error::NotFound("Parent directory not found".to_string()))? + .to_path_buf(); + + // We download this code to the UV directory + let exe = install::download_uv_for_arch(&parent).await?; + + // Target is the UV binary we want. + let target = path.join("uv"); + + // Copy the `uv` binary into the default directory + std::fs::copy(&exe, &target) + .map_err(|e| Error::IoError(e))?; + + Ok(target) + } +} + +pub struct Uv { + pub uv_path: PathBuf, +} + +impl Uv { + pub async fn new() -> Result { + let uv_path = find_or_setup_uv().await?; + Ok(Uv { uv_path }) + } + + pub async fn venv(&self, cwd: &PathBuf, env_vars: &HashMap) -> Result { + debug!("Executing UV ({:?}) venv in {:?}", &self.uv_path, cwd); + + let child = Command::new(&self.uv_path) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .current_dir(cwd) + .arg("venv") + .envs(env_vars) + .spawn()?; + + Ok(child) + } + + pub async fn sync(&self, cwd: &PathBuf, env_vars: &HashMap) -> Result { + debug!("Executing UV ({:?}) sync in {:?}", &self.uv_path, cwd); + + let child = Command::new(&self.uv_path) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .current_dir(cwd) + .arg("--color") + .arg("never") + .arg("--no-progress") + .arg("sync") + .envs(env_vars) + .spawn()?; + + Ok(child) + } + + pub async fn run(&self, cwd: &PathBuf, program: &PathBuf, env_vars: &HashMap) -> Result { + debug!("Executing UV ({:?}) run {:?} in {:?}", &self.uv_path, program, cwd); + + let child = Command::new(&self.uv_path) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .current_dir(cwd) + .arg("--color") + .arg("never") + .arg("--no-progress") + .arg("run") + .arg(program) + .envs(env_vars) + .spawn()?; + + Ok(child) + } +}