|
| 1 | +use crate::packaging_tool_versions::PIP_VERSION; |
| 2 | +use crate::python_version::PythonVersion; |
| 3 | +use crate::utils::StreamedCommandError; |
| 4 | +use crate::{utils, BuildpackError, PythonBuildpack}; |
| 5 | +use libcnb::build::BuildContext; |
| 6 | +use libcnb::data::layer_name; |
| 7 | +use libcnb::layer::{ |
| 8 | + CachedLayerDefinition, EmptyLayerCause, InvalidMetadataAction, LayerState, RestoredLayerAction, |
| 9 | +}; |
| 10 | +use libcnb::layer_env::{LayerEnv, ModificationBehavior, Scope}; |
| 11 | +use libcnb::Env; |
| 12 | +use libherokubuildpack::log::log_info; |
| 13 | +use serde::{Deserialize, Serialize}; |
| 14 | +use std::io; |
| 15 | +use std::path::Path; |
| 16 | +use std::process::Command; |
| 17 | + |
| 18 | +/// Creates a layer containing pip. |
| 19 | +pub(crate) fn install_pip( |
| 20 | + context: &BuildContext<PythonBuildpack>, |
| 21 | + env: &mut Env, |
| 22 | + python_version: &PythonVersion, |
| 23 | + python_layer_path: &Path, |
| 24 | +) -> Result<(), libcnb::Error<BuildpackError>> { |
| 25 | + let new_metadata = PipLayerMetadata { |
| 26 | + python_version: python_version.to_string(), |
| 27 | + pip_version: PIP_VERSION.to_string(), |
| 28 | + }; |
| 29 | + |
| 30 | + let layer = context.cached_layer( |
| 31 | + layer_name!("pip"), |
| 32 | + CachedLayerDefinition { |
| 33 | + build: true, |
| 34 | + launch: true, |
| 35 | + invalid_metadata_action: &|_| InvalidMetadataAction::DeleteLayer, |
| 36 | + restored_layer_action: &|cached_metadata: &PipLayerMetadata, _| { |
| 37 | + let cached_pip_version = cached_metadata.pip_version.clone(); |
| 38 | + if cached_metadata == &new_metadata { |
| 39 | + (RestoredLayerAction::KeepLayer, cached_pip_version) |
| 40 | + } else { |
| 41 | + (RestoredLayerAction::DeleteLayer, cached_pip_version) |
| 42 | + } |
| 43 | + }, |
| 44 | + }, |
| 45 | + )?; |
| 46 | + |
| 47 | + let mut layer_env = LayerEnv::new() |
| 48 | + // We use a curated pip version, so disable the update check to speed up pip invocations, |
| 49 | + // reduce build log spam and prevent users from thinking they need to manually upgrade. |
| 50 | + // https://pip.pypa.io/en/stable/cli/pip/#cmdoption-disable-pip-version-check |
| 51 | + .chainable_insert( |
| 52 | + Scope::All, |
| 53 | + ModificationBehavior::Override, |
| 54 | + "PIP_DISABLE_PIP_VERSION_CHECK", |
| 55 | + "1", |
| 56 | + ) |
| 57 | + // Move the Python user base directory to this layer instead of under HOME: |
| 58 | + // https://docs.python.org/3/using/cmdline.html#envvar-PYTHONUSERBASE |
| 59 | + .chainable_insert( |
| 60 | + Scope::All, |
| 61 | + ModificationBehavior::Override, |
| 62 | + "PYTHONUSERBASE", |
| 63 | + layer.path(), |
| 64 | + ); |
| 65 | + |
| 66 | + match layer.state { |
| 67 | + LayerState::Restored { |
| 68 | + cause: ref cached_pip_version, |
| 69 | + } => { |
| 70 | + log_info(format!("Using cached pip {cached_pip_version}")); |
| 71 | + } |
| 72 | + LayerState::Empty { ref cause } => { |
| 73 | + match cause { |
| 74 | + EmptyLayerCause::InvalidMetadataAction { .. } => { |
| 75 | + log_info("Discarding cached pip since its layer metadata can't be parsed"); |
| 76 | + } |
| 77 | + EmptyLayerCause::RestoredLayerAction { |
| 78 | + cause: cached_pip_version, |
| 79 | + } => { |
| 80 | + log_info(format!("Discarding cached pip {cached_pip_version}")); |
| 81 | + } |
| 82 | + EmptyLayerCause::NewlyCreated => {} |
| 83 | + } |
| 84 | + |
| 85 | + log_info(format!("Installing pip {PIP_VERSION}")); |
| 86 | + |
| 87 | + // We use the pip wheel bundled within Python's standard library to install our chosen |
| 88 | + // pip version, since it's faster than `ensurepip` followed by an upgrade in place. |
| 89 | + let bundled_pip_module_path = |
| 90 | + utils::bundled_pip_module_path(python_layer_path, python_version) |
| 91 | + .map_err(PipLayerError::LocateBundledPip)?; |
| 92 | + |
| 93 | + utils::run_command_and_stream_output( |
| 94 | + Command::new("python") |
| 95 | + .args([ |
| 96 | + &bundled_pip_module_path.to_string_lossy(), |
| 97 | + "install", |
| 98 | + // There is no point using pip's cache here, since the layer itself will be cached. |
| 99 | + "--no-cache-dir", |
| 100 | + "--no-input", |
| 101 | + "--no-warn-script-location", |
| 102 | + "--quiet", |
| 103 | + "--user", |
| 104 | + format!("pip=={PIP_VERSION}").as_str(), |
| 105 | + ]) |
| 106 | + .env_clear() |
| 107 | + .envs(&layer_env.apply(Scope::Build, env)), |
| 108 | + ) |
| 109 | + .map_err(PipLayerError::InstallPipCommand)?; |
| 110 | + |
| 111 | + layer.write_metadata(new_metadata)?; |
| 112 | + } |
| 113 | + } |
| 114 | + |
| 115 | + layer.write_env(&layer_env)?; |
| 116 | + // Required to pick up the automatic PATH env var. See: https://github.com/heroku/libcnb.rs/issues/842 |
| 117 | + layer_env = layer.read_env()?; |
| 118 | + env.clone_from(&layer_env.apply(Scope::Build, env)); |
| 119 | + |
| 120 | + Ok(()) |
| 121 | +} |
| 122 | + |
| 123 | +// pip's wheel is a pure Python package with no dependencies, so the layer is not arch or distro |
| 124 | +// specific. However, the generated .pyc files vary by Python version. |
| 125 | +#[derive(Deserialize, PartialEq, Serialize)] |
| 126 | +#[serde(deny_unknown_fields)] |
| 127 | +struct PipLayerMetadata { |
| 128 | + python_version: String, |
| 129 | + pip_version: String, |
| 130 | +} |
| 131 | + |
| 132 | +/// Errors that can occur when installing pip into a layer. |
| 133 | +#[derive(Debug)] |
| 134 | +pub(crate) enum PipLayerError { |
| 135 | + InstallPipCommand(StreamedCommandError), |
| 136 | + LocateBundledPip(io::Error), |
| 137 | +} |
| 138 | + |
| 139 | +impl From<PipLayerError> for libcnb::Error<BuildpackError> { |
| 140 | + fn from(error: PipLayerError) -> Self { |
| 141 | + Self::BuildpackError(BuildpackError::PipLayer(error)) |
| 142 | + } |
| 143 | +} |
0 commit comments