Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Trialing "struct-api" #299

Closed
wants to merge 2 commits into from
Closed
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
53 changes: 43 additions & 10 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion buildpacks/ruby/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ glob = "0.3"
indoc = "2"
# libcnb has a much bigger impact on buildpack behaviour than any other dependencies,
# so it's pinned to an exact version to isolate it from lockfile refreshes.
libcnb = "=0.21.0"
libcnb = { git = "https://github.com/heroku/libcnb.rs", branch = "malax/layer-api" }
libherokubuildpack = { version = "=0.21.0", default-features = false, features = ["digest"] }
rand = "0.8"
# TODO: Consolidate on either the regex crate or the fancy-regex crate, since this repo currently uses both.
Expand Down
101 changes: 4 additions & 97 deletions buildpacks/ruby/src/layers/metrics_agent_install.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ use tempfile::NamedTempFile;
/// ```shell
/// $ curl https://agentmon-releases.s3.us-east-1.amazonaws.com/latest
/// ```
const DOWNLOAD_URL: &str =
pub(crate) const DOWNLOAD_URL: &str =
"https://agentmon-releases.s3.us-east-1.amazonaws.com/agentmon-0.3.1-linux-amd64.tar.gz";
const DOWNLOAD_SHA: &str = "f9bf9f33c949e15ffed77046ca38f8dae9307b6a0181c6af29a25dec46eb2dac";

Expand All @@ -36,7 +36,7 @@ pub(crate) struct MetricsAgentInstall<'a> {

#[derive(Deserialize, Serialize, Debug, Clone)]
pub(crate) struct Metadata {
download_url: Option<String>,
pub(crate) download_url: Option<String>,
}

#[derive(thiserror::Error, Debug)]
Expand Down Expand Up @@ -64,100 +64,7 @@ pub(crate) enum MetricsAgentInstallError {
ChecksumFailed(String),
}

impl<'a> Layer for MetricsAgentInstall<'a> {
type Buildpack = RubyBuildpack;
type Metadata = Metadata;

fn types(&self) -> libcnb::data::layer_content_metadata::LayerTypes {
LayerTypes {
build: true,
launch: true,
cache: true,
}
}

fn create(
&mut self,
_context: &libcnb::build::BuildContext<Self::Buildpack>,
layer_path: &std::path::Path,
) -> Result<
libcnb::layer::LayerResult<Self::Metadata>,
<Self::Buildpack as libcnb::Buildpack>::Error,
> {
let bin_dir = layer_path.join("bin");

let agentmon = log_step_timed("Downloading", || {
install_agentmon(&bin_dir).map_err(RubyBuildpackError::MetricsAgentError)
})?;

log_step("Writing scripts");
let execd = write_execd_script(&agentmon, layer_path)
.map_err(RubyBuildpackError::MetricsAgentError)?;

LayerResultBuilder::new(Metadata {
download_url: Some(DOWNLOAD_URL.to_string()),
})
.exec_d_program("spawn_metrics_agent", execd)
.build()
}

fn update(
&mut self,
_context: &libcnb::build::BuildContext<Self::Buildpack>,
layer_data: &libcnb::layer::LayerData<Self::Metadata>,
) -> Result<
libcnb::layer::LayerResult<Self::Metadata>,
<Self::Buildpack as libcnb::Buildpack>::Error,
> {
let layer_path = &layer_data.path;

log_step("Writing scripts");
let execd = write_execd_script(&layer_path.join("bin").join("agentmon"), layer_path)
.map_err(RubyBuildpackError::MetricsAgentError)?;

LayerResultBuilder::new(Metadata {
download_url: Some(DOWNLOAD_URL.to_string()),
})
.exec_d_program("spawn_metrics_agent", execd)
.build()
}

fn existing_layer_strategy(
&mut self,
_context: &libcnb::build::BuildContext<Self::Buildpack>,
layer_data: &libcnb::layer::LayerData<Self::Metadata>,
) -> Result<libcnb::layer::ExistingLayerStrategy, <Self::Buildpack as libcnb::Buildpack>::Error>
{
match &layer_data.content_metadata.metadata.download_url {
Some(url) if url == DOWNLOAD_URL => {
log_step("Using cached metrics agent");
Ok(ExistingLayerStrategy::Update)
}
Some(url) => {
log_step(format!(
"Using cached metrics agent ({url} to {DOWNLOAD_URL}"
));
Ok(ExistingLayerStrategy::Recreate)
}
None => Ok(ExistingLayerStrategy::Recreate),
}
}

fn migrate_incompatible_metadata(
&mut self,
_context: &libcnb::build::BuildContext<Self::Buildpack>,
_metadata: &GenericMetadata,
) -> Result<
libcnb::layer::MetadataMigration<Self::Metadata>,
<Self::Buildpack as libcnb::Buildpack>::Error,
> {
log_step("Clearing cache (invalid metadata)");

Ok(libcnb::layer::MetadataMigration::RecreateLayer)
}
}

fn write_execd_script(
pub(crate) fn write_execd_script(
agentmon: &Path,
layer_path: &Path,
) -> Result<PathBuf, MetricsAgentInstallError> {
Expand Down Expand Up @@ -200,7 +107,7 @@ fn write_execd_script(
Ok(execd)
}

fn install_agentmon(dir: &Path) -> Result<PathBuf, MetricsAgentInstallError> {
pub(crate) fn install_agentmon(dir: &Path) -> Result<PathBuf, MetricsAgentInstallError> {
let agentmon = download_untar(DOWNLOAD_URL, dir).map(|()| dir.join("agentmon"))?;

chmod_plus_x(&agentmon).map_err(MetricsAgentInstallError::PermissionError)?;
Expand Down
69 changes: 63 additions & 6 deletions buildpacks/ruby/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ use libcnb::data::launch::LaunchBuilder;
use libcnb::data::layer_name;
use libcnb::detect::{DetectContext, DetectResult, DetectResultBuilder};
use libcnb::generic::{GenericMetadata, GenericPlatform};
use libcnb::layer_env::Scope;
use libcnb::layer::{CachedLayerDefinition, InspectRestoredAction, InvalidMetadataAction};
use libcnb::layer_env::{LayerEnv, Scope};
use libcnb::Platform;
use libcnb::{buildpack_main, Buildpack};
use std::io::stdout;
Expand Down Expand Up @@ -132,18 +133,74 @@ impl Buildpack for RubyBuildpack {

// ## Install metrics agent
(logger, env) = {
let section = logger.section("Metrics agent");
let mut section = logger.section("Metrics agent");
if lockfile_contents.contains("barnes") {
let layer_data = context.handle_layer(
let metrics_layer = context.cached_layer(
layer_name!("metrics_agent"),
MetricsAgentInstall {
_in_section: section.as_ref(),
CachedLayerDefinition {
build: true,
launch: true,
invalid_metadata: &|_| {
// TODO, cannot log here
// section = section.step("Clearing invalid metadata");
InvalidMetadataAction::DeleteLayer
},
inspect_restored: &|old: &layers::metrics_agent_install::Metadata, _| {
match &old.download_url.as_ref() {
&Some(old_url) => {
if old_url == layers::metrics_agent_install::DOWNLOAD_URL {
InspectRestoredAction::KeepLayer
} else {
// TODO, cannot log here
// section = section.step(&format!(
// "Download URL changed from {old} to {now}",
// old = fmt::value(&old_url),
// now = fmt::value(
// layers::metrics_agent_install::DOWNLOAD_URL
// )
// ));
InspectRestoredAction::DeleteLayer
}
}
None => InspectRestoredAction::DeleteLayer,
}
},
},
)?;

match metrics_layer.state {
libcnb::layer::LayerState::Restored { .. } => {
section = section.step("Using cached metrics agent");
}
libcnb::layer::LayerState::Empty { .. } => {
let timer = section.step_timed("Downloading metrics agent");
layers::metrics_agent_install::install_agentmon(
&metrics_layer.path().join("bin"),
)
.map_err(RubyBuildpackError::MetricsAgentError)?;
section = timer.finish_timed_step();
}
};

let agentmon_path = metrics_layer.path().join("bin").join("agentmon");
section = section.step("Writing scripts");
let execd = layers::metrics_agent_install::write_execd_script(
&agentmon_path,
&metrics_layer.path(),
)
.map_err(RubyBuildpackError::MetricsAgentError)?;

metrics_layer.replace_metadata(layers::metrics_agent_install::Metadata {
download_url: Some(layers::metrics_agent_install::DOWNLOAD_URL.to_string()),
})?;

metrics_layer.replace_exec_d_programs(vec![("spawn_metrics_agent", execd)])?;

(
section.end_section(),
layer_data.env.apply(Scope::Build, &env),
LayerEnv::read_from_layer_dir(metrics_layer.path())
.expect("read env from a layer")
.apply(Scope::Build, &env),
)
} else {
(
Expand Down
3 changes: 2 additions & 1 deletion commons/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ indoc = "2"
lazy_static = "1"
# libcnb has a much bigger impact on buildpack behaviour than any other dependencies,
# so it's pinned to an exact version to isolate it from lockfile refreshes.
libcnb = "=0.21.0"

libcnb = { git = "https://github.com/heroku/libcnb.rs", branch = "malax/layer-api" }
libherokubuildpack = { version = "=0.21.0", default-features = false, features = ["command"] }
regex = "1"
serde = "1"
Expand Down
Loading