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

Add a gh-action and buildomat jobs to cargo check on no-default-features and feature-powerset #6018

Merged
merged 4 commits into from
Jul 16, 2024
Merged
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
1 change: 1 addition & 0 deletions .cargo/config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
# CI scripts:
# - .github/buildomat/build-and-test.sh
# - .github/buildomat/jobs/clippy.sh
# - .github/buildomat/jobs/check-features.sh
# - .github/workflows/rust.yml
#
[build]
Expand Down
34 changes: 34 additions & 0 deletions .github/buildomat/jobs/check-features.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#!/bin/bash
#:
#: name = "check-features (helios)"
#: variety = "basic"
#: target = "helios-2.0"
#: rust_toolchain = true
#: output_rules = [
#: "/out/*",
#: ]

# Run the check-features `xtask` on illumos, testing compilation of feature combinations.

set -o errexit
set -o pipefail
set -o xtrace

cargo --version
rustc --version

#
# Set up our PATH for use with this workspace.
#
source ./env.sh
export PATH="$PATH:$PWD/out/cargo-hack"

banner prerequisites
ptime -m bash ./tools/install_builder_prerequisites.sh -y

#
# Check feature combinations with the `cargo xtask check-features` command.
#
banner hack-check
export CARGO_INCREMENTAL=0
ptime -m timeout 2h cargo xtask check-features --ci
2 changes: 1 addition & 1 deletion .github/buildomat/jobs/clippy.sh
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
# (that we want to check) is conditionally-compiled on illumos only.
#
# Note that `cargo clippy` includes `cargo check, so this ends up checking all
# of our code.
# of our (default) code.

set -o errexit
set -o pipefail
Expand Down
32 changes: 31 additions & 1 deletion .github/workflows/rust.yml
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ jobs:
run: cargo run --bin omicron-package -- -t default check

# Note that `cargo clippy` includes `cargo check, so this ends up checking all
# of our code.
# of our (default) code.
clippy-lint:
runs-on: ubuntu-22.04
env:
Expand Down Expand Up @@ -82,6 +82,36 @@ jobs:
- name: Run Clippy Lints
run: cargo xtask clippy

check-features:
zeeshanlakhani marked this conversation as resolved.
Show resolved Hide resolved
runs-on: ubuntu-22.04
env:
CARGO_INCREMENTAL: 0
steps:
# This repo is unstable and unnecessary: https://github.com/microsoft/linux-package-repositories/issues/34
- name: Disable packages.microsoft.com repo
run: sudo rm -f /etc/apt/sources.list.d/microsoft-prod.list
- uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
with:
ref: ${{ github.event.pull_request.head.sha }} # see omicron#4461
- uses: Swatinem/rust-cache@23bce251a8cd2ffc3c1075eaa2367cf899916d84 # v2.7.3
if: ${{ github.ref != 'refs/heads/main' }}
- name: Report cargo version
run: cargo --version
- name: Update PATH
run: |
set -x
export PATH="./out/cargo-hack:$PATH"
source "./env.sh"; echo "PATH=$PATH" >> "$GITHUB_ENV"
- name: Print PATH
run: echo $PATH
- name: Print GITHUB_ENV
run: cat "$GITHUB_ENV"
- name: Install Pre-Requisites
run: ./tools/install_builder_prerequisites.sh -y
- name: Run Check on Feature Combinations (Feature-Powerset, No-Dev-Deps)
timeout-minutes: 120 # 2 hours
run: cargo xtask check-features --ci

# This is just a test build of docs. Publicly available docs are built via
# the separate "rustdocs" repo.
build-docs:
Expand Down
15 changes: 15 additions & 0 deletions README.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,21 @@ cargo nextest run

We check that certain system library dependencies are not leaked outside of their intended binaries via `cargo xtask verify-libraries` in CI. If you are adding a new dependency on a illumos/helios library it is recommended that you update xref:.cargo/xtask.toml[] with an allow list of where you expect the dependency to show up. For example some libraries such as `libnvme.so.1` are only available in the global zone and therefore will not be present in any other zone. This check is here to help us catch any leakage before we go to deploy on a rack. You can inspect a compiled binary in the target directory for what it requires by using `elfedit` - for example `elfedit -r -e 'dyn:tag NEEDED' /path/to/omicron/target/debug/sled-agent`.

=== Checking feature flag combinations

To ensure that varying combinations of features compile, run `cargo xtask check-features`, which executes the https://github.com/taiki-e/cargo-hack[`cargo hack`] subcommand under the hood.

This `xtask` is run in CI using the `--ci` parameter , which automatically exludes certain `image-*` features that purposefully cause compiler errors if set and uses a pre-built binary.

If `cargo hack` is not already installed in omicron's `out/` directory, a pre-built binary will be installed automatically depending on your operating system and architecture.

To limit the max number of simultaneous feature flags combined for checking, run the `xtask` with the `--depth <NUM>` flag:

[source,text]
----
$ cargo xtask check-features --depth 2
----

=== Rust packages in Omicron

NOTE: The term "package" is overloaded: most programming languages and operating systems have their own definitions of a package. On top of that, Omicron bundles up components into our own kind of "package" that gets delivered via the install and update systems. These are described in the `package-manifest.toml` file in the root of the repo. In this section, we're just concerned with Rust packages.
Expand Down
212 changes: 212 additions & 0 deletions dev-tools/xtask/src/check_features.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,212 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

//! Subcommand: cargo xtask check-features

use anyhow::{bail, Result};
use camino::Utf8PathBuf;
use clap::Parser;
use std::{collections::HashSet, process::Command};

const SUPPORTED_ARCHITECTURES: [&str; 1] = ["x86_64"];
const CI_EXCLUDED_FEATURES: [&str; 2] = ["image-trampoline", "image-standard"];

#[derive(Parser)]
pub struct Args {
/// Run in CI mode, with a default set of features excluded.
#[clap(long, default_value_t = false)]
ci: bool,
/// Features to exclude from the check.
#[clap(long, value_name = "FEATURES")]
exclude_features: Option<Vec<String>>,
/// Depth of the feature powerset to check.
#[clap(long, value_name = "NUM")]
depth: Option<usize>,
/// Error format passed to `cargo hack check`.
#[clap(long, value_name = "FMT")]
message_format: Option<String>,
/// Version of `cargo-hack` to install. By default, we download a pre-built
/// version.
#[clap(long, value_name = "VERSION")]
install_version: Option<String>,
}

/// Run `cargo hack check`.
pub fn run_cmd(args: Args) -> Result<()> {
// We cannot specify both `--ci` and `--install-version`, as the former
// implies we are using a pre-built version.
if args.ci && args.install_version.is_some() {
bail!("cannot specify --ci and --install-version together");
}

let cargo =
std::env::var("CARGO").unwrap_or_else(|_| String::from("cargo"));

let mut command = Command::new(&cargo);

// Add the `hack check` subcommand.
command.args(&["hack", "check"]);

if args.ci {
install_prebuilt_cargo_hack(&cargo)?;

let ex = if let Some(mut features) = args.exclude_features {
// Extend the list of features to exclude with the CI defaults.
features.extend(
CI_EXCLUDED_FEATURES.into_iter().map(|s| s.to_string()),
);

// Remove duplicates.
let excludes = features.into_iter().collect::<HashSet<_>>();

excludes.into_iter().collect::<Vec<_>>().join(",")
} else {
CI_EXCLUDED_FEATURES.join(",")
};

// Add the `--exclude-features` flag if we are running in CI mode.
command.args(["--exclude-features", &ex]);
} else {
install_cargo_hack(&cargo, args.install_version)?;
// Add "only" the `--exclude-features` flag if it was provided.
if let Some(features) = args.exclude_features {
command.args(["--exclude-features", &features.join(",")]);
}
}

if let Some(depth) = args.depth {
command.args(&["--depth", &depth.to_string()]);
}

// Pass along the `--message-format` flag if it was provided.
if let Some(fmt) = args.message_format {
command.args(["--message-format", &fmt]);
}

command
// Make sure we check everything.
.arg("--workspace")
// We want to check the binaries.
.arg("--bins")
// We want to check the feature powerset.
.arg("--feature-powerset")
// We will not check the dev-dependencies, which should covered by tests.
.arg("--no-dev-deps");

exec(command)
}

/// The supported operating systems.
enum Os {
Illumos,
Linux,
Mac,
}

/// Get the current OS.
fn os_name() -> Result<Os> {
let os = match std::env::consts::OS {
"linux" => Os::Linux,
"macos" => Os::Mac,
"solaris" | "illumos" => Os::Illumos,
other => bail!("OS not supported: {other}"),
};
Ok(os)
}

/// This is a workaround for the lack of a CARGO_WORKSPACE_DIR environment
/// variable, as suggested in <https://github.com/rust-lang/cargo/issues/3946#issuecomment-1433384192>.
/// A better workaround might be to set this in the `[env]` section of
/// `.cargo/config.toml`.
fn project_root() -> Utf8PathBuf {
Utf8PathBuf::from(&concat!(env!("CARGO_MANIFEST_DIR"), "/.."))
}

/// Get the path to the `out` directory from the project root/workspace
/// directory.
fn out_dir() -> Utf8PathBuf {
project_root().join("out/cargo-hack")
}

/// Install `cargo-hack` if the `install-version` was specified; otherwise,
/// download a pre-built version if it's not already in our `out` directory.
fn install_cargo_hack(cargo: &str, version: Option<String>) -> Result<()> {
if let Some(version) = version {
let mut command = Command::new(cargo);

eprintln!(
"installing cargo-hack at version {} to {}",
version,
env!("CARGO_HOME")
);
command.args(&["install", "cargo-hack", "--version", &version]);
exec(command)
} else if !out_dir().exists() {
install_prebuilt_cargo_hack(cargo)
} else {
let out_dir = out_dir();
eprintln!("cargo-hack found in {}", out_dir);
Ok(())
}
}

/// Download a pre-built version of `cargo-hack` to the `out` directory via the
/// download `xtask`.
fn install_prebuilt_cargo_hack(cargo: &str) -> Result<()> {
let mut command = Command::new(cargo);

let out_dir = out_dir();
eprintln!(
"cargo-hack not found in {}, downloading a pre-built version",
out_dir
);

let os = os_name()?;
match os {
Os::Illumos | Os::Linux | Os::Mac
if SUPPORTED_ARCHITECTURES.contains(&std::env::consts::ARCH) =>
{
// Download the pre-built version of `cargo-hack` via our
// download `xtask`.
command.args(&["xtask", "download", "cargo-hack"]);
}
_ => {
bail!(
"cargo-hack is not pre-built for this os {} / arch {}",
std::env::consts::OS,
std::env::consts::ARCH
);
}
}

exec(command)
}

/// Execute the command and check the exit status.
fn exec(mut command: Command) -> Result<()> {
let cargo =
std::env::var("CARGO").unwrap_or_else(|_| String::from("cargo"));

eprintln!(
"running: {:?} {}",
&cargo,
command
.get_args()
.map(|arg| format!("{:?}", arg.to_str().unwrap()))
.collect::<Vec<_>>()
.join(" ")
);

let exit_status = command
.spawn()
.expect("failed to spawn child process")
.wait()
.expect("failed to wait for child process");

if !exit_status.success() {
bail!("cargo-hack install failed: {}", exit_status);
}

Ok(())
}
Loading
Loading