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

Migrate metrics agent layer to Struct API and bullet Stream #321

Merged
merged 7 commits into from
Sep 23, 2024
Merged
Show file tree
Hide file tree
Changes from 6 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
68 changes: 56 additions & 12 deletions Cargo.lock

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

3 changes: 2 additions & 1 deletion buildpacks/ruby/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ rust-version.workspace = true
workspace = true

[dependencies]
bullet_stream = "0.2.0"
clap = { version = "4", default-features = false, features = ["derive", "error-context", "help", "std", "usage"] }
commons = { path = "../../commons" }
flate2 = { version = "1", default-features = false, features = ["zlib"] }
Expand All @@ -16,7 +17,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 = "=0.23.0"
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
154 changes: 58 additions & 96 deletions buildpacks/ruby/src/layers/metrics_agent_install.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
use crate::{RubyBuildpack, RubyBuildpackError};
use commons::output::section_log::{log_step, log_step_timed, SectionLogger};
use bullet_stream::state::SubBullet;
use bullet_stream::Print;
use flate2::read::GzDecoder;
use libcnb::data::layer_content_metadata::LayerTypes;
use libcnb::layer::ExistingLayerStrategy;
use libcnb::{
additional_buildpack_binary_path,
generic::GenericMetadata,
layer::{Layer, LayerResultBuilder},
use libcnb::additional_buildpack_binary_path;
use libcnb::data::layer_name;
use libcnb::layer::{
CachedLayerDefinition, EmptyLayerCause, InvalidMetadataAction, LayerState, RestoredLayerAction,
};
use libherokubuildpack::digest::sha256;
use serde::{Deserialize, Serialize};
use std::io::Stdout;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use tar::Archive;
Expand All @@ -29,14 +29,9 @@ 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";

#[derive(Debug)]
pub(crate) struct MetricsAgentInstall<'a> {
pub(crate) _in_section: &'a dyn SectionLogger, // force the layer to be called within a Section logging context, not necessary but it's safer
}

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

#[derive(thiserror::Error, Debug)]
Expand Down Expand Up @@ -64,97 +59,64 @@ 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 {
pub(crate) fn handle_metrics_agent_layer(
context: &libcnb::build::BuildContext<RubyBuildpack>,
mut bullet: Print<SubBullet<Stdout>>,
) -> libcnb::Result<Print<SubBullet<Stdout>>, RubyBuildpackError> {
let layer_ref = context.cached_layer(
layer_name!("metrics_agent"),
CachedLayerDefinition {
build: true,
launch: true,
cache: true,
invalid_metadata_action: &|_| InvalidMetadataAction::DeleteLayer,
restored_layer_action: &|metadata: &Metadata, _| {
if metadata.download_url == DOWNLOAD_URL {
(
RestoredLayerAction::KeepLayer,
metadata.download_url.clone(),
)
} else {
(
RestoredLayerAction::DeleteLayer,
metadata.download_url.clone(),
)
}
},
},
)?;

match layer_ref.state.clone() {
LayerState::Restored { .. } => {
bullet = bullet.sub_bullet("Using cached metrics agent");
}
}

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)?;
LayerState::Empty { cause } => {
match cause {
EmptyLayerCause::NewlyCreated => {}
EmptyLayerCause::InvalidMetadataAction { .. } => {
bullet = bullet.sub_bullet("Clearing cache (invalid metadata)");
}
EmptyLayerCause::RestoredLayerAction { cause: url } => {
bullet = bullet.sub_bullet(format!("Deleting cached metrics agent ({url})"));
}
}
let bin_dir = layer_ref.path().join("bin");

LayerResultBuilder::new(Metadata {
download_url: Some(DOWNLOAD_URL.to_string()),
})
.exec_d_program("spawn_metrics_agent", execd)
.build()
}
let timer = bullet.start_timer(format!("Installing metrics agent from {DOWNLOAD_URL}"));
let agentmon =
install_agentmon(&bin_dir).map_err(RubyBuildpackError::MetricsAgentError)?;
bullet = timer.done();

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()
}
bullet = bullet.sub_bullet("Writing scripts");
let execd = write_execd_script(&agentmon, layer_ref.path().as_path())
.map_err(RubyBuildpackError::MetricsAgentError)?;

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),
layer_ref.write_exec_d_programs([("spawn_metrics_agent".to_string(), execd)])?;
layer_ref.write_metadata(Metadata {
download_url: DOWNLOAD_URL.to_string(),
})?;
}
}

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)
}
Ok(bullet)
}

fn write_execd_script(
Expand Down
35 changes: 12 additions & 23 deletions buildpacks/ruby/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use bullet_stream::{style, Print};
use commons::cache::CacheError;
use commons::gemfile_lock::GemfileLock;
use commons::metadata_digest::MetadataDigest;
Expand All @@ -10,7 +11,7 @@ use fun_run::CmdError;
use layers::{
bundle_download_layer::{BundleDownloadLayer, BundleDownloadLayerMetadata},
bundle_install_layer::{BundleInstallLayer, BundleInstallLayerMetadata},
metrics_agent_install::{MetricsAgentInstall, MetricsAgentInstallError},
metrics_agent_install::MetricsAgentInstallError,
ruby_install_layer::{RubyInstallError, RubyInstallLayer, RubyInstallLayerMetadata},
};
use libcnb::build::{BuildContext, BuildResult, BuildResultBuilder};
Expand Down Expand Up @@ -130,31 +131,19 @@ impl Buildpack for RubyBuildpack {
let bundler_version = gemfile_lock.resolve_bundler("2.4.5");
let ruby_version = gemfile_lock.resolve_ruby("3.1.3");

let mut build_output = Print::new(stdout()).without_header();
// ## Install metrics agent
(logger, env) = {
let section = logger.section("Metrics agent");
build_output = {
let bullet = build_output.bullet("Metrics agent");
if lockfile_contents.contains("barnes") {
let layer_data = context.handle_layer(
layer_name!("metrics_agent"),
MetricsAgentInstall {
_in_section: section.as_ref(),
},
)?;

(
section.end_section(),
layer_data.env.apply(Scope::Build, &env),
)
layers::metrics_agent_install::handle_metrics_agent_layer(&context, bullet)?.done()
} else {
(
section
.step(&format!(
"Skipping install ({barnes} gem not found)",
barnes = fmt::value("barnes")
))
.end_section(),
env,
)
bullet
.sub_bullet(&format!(
"Skipping install ({barnes} gem not found)",
barnes = style::value("barnes")
))
.done()
}
};

Expand Down
Loading
Loading